@zaip-ai/cli 4.8.0 → 5.0.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 (195) hide show
  1. package/dist/services/adapter-hook-sources.d.ts +3 -0
  2. package/dist/services/adapter-hook-sources.d.ts.map +1 -1
  3. package/dist/services/adapter-hook-sources.js +3 -0
  4. package/dist/services/adapter-hook-sources.js.map +1 -1
  5. package/dist/services/adapters.d.ts +1 -1
  6. package/dist/services/adapters.d.ts.map +1 -1
  7. package/dist/services/adapters.js +5 -2
  8. package/dist/services/adapters.js.map +1 -1
  9. package/dist/services/adapters.test.js +1 -1
  10. package/dist/services/adapters.test.js.map +1 -1
  11. package/dist/services/codex-conversation-lifecycle-hook.d.ts.map +1 -1
  12. package/dist/services/codex-conversation-lifecycle-hook.js +16 -6
  13. package/dist/services/codex-conversation-lifecycle-hook.js.map +1 -1
  14. package/dist/services/codex-hook-activation.d.ts +1 -1
  15. package/dist/services/codex-hook-activation.d.ts.map +1 -1
  16. package/dist/services/codex-hook-activation.js +116 -10
  17. package/dist/services/codex-hook-activation.js.map +1 -1
  18. package/dist/services/codex-pre-tool-cli-capture-template.d.ts +2 -0
  19. package/dist/services/codex-pre-tool-cli-capture-template.d.ts.map +1 -0
  20. package/dist/services/codex-pre-tool-cli-capture-template.js +104 -0
  21. package/dist/services/codex-pre-tool-cli-capture-template.js.map +1 -0
  22. package/dist/services/codex-pre-tool-cloud-template.d.ts +2 -0
  23. package/dist/services/codex-pre-tool-cloud-template.d.ts.map +1 -0
  24. package/dist/services/codex-pre-tool-cloud-template.js +190 -0
  25. package/dist/services/codex-pre-tool-cloud-template.js.map +1 -0
  26. package/dist/services/codex-pre-tool-dependencies.test-support.d.ts +2 -0
  27. package/dist/services/codex-pre-tool-dependencies.test-support.d.ts.map +1 -0
  28. package/dist/services/codex-pre-tool-dependencies.test-support.js +9 -0
  29. package/dist/services/codex-pre-tool-dependencies.test-support.js.map +1 -0
  30. package/dist/services/codex-pre-tool-hook-fixture.test-support.d.ts +5 -0
  31. package/dist/services/codex-pre-tool-hook-fixture.test-support.d.ts.map +1 -0
  32. package/dist/services/codex-pre-tool-hook-fixture.test-support.js +19 -0
  33. package/dist/services/codex-pre-tool-hook-fixture.test-support.js.map +1 -0
  34. package/dist/services/codex-pre-tool-hook-template-bootstrap.test.d.ts +2 -0
  35. package/dist/services/codex-pre-tool-hook-template-bootstrap.test.d.ts.map +1 -0
  36. package/dist/services/codex-pre-tool-hook-template-bootstrap.test.js +107 -0
  37. package/dist/services/codex-pre-tool-hook-template-bootstrap.test.js.map +1 -0
  38. package/dist/services/codex-pre-tool-hook-template.d.ts.map +1 -1
  39. package/dist/services/codex-pre-tool-hook-template.js +152 -190
  40. package/dist/services/codex-pre-tool-hook-template.js.map +1 -1
  41. package/dist/services/codex-pre-tool-hook-template.test.js +63 -75
  42. package/dist/services/codex-pre-tool-hook-template.test.js.map +1 -1
  43. package/dist/services/codex-pre-tool-host-context-template.d.ts +2 -0
  44. package/dist/services/codex-pre-tool-host-context-template.d.ts.map +1 -0
  45. package/dist/services/codex-pre-tool-host-context-template.js +139 -0
  46. package/dist/services/codex-pre-tool-host-context-template.js.map +1 -0
  47. package/dist/services/codex-pre-tool-support-template.d.ts.map +1 -1
  48. package/dist/services/codex-pre-tool-support-template.js +77 -100
  49. package/dist/services/codex-pre-tool-support-template.js.map +1 -1
  50. package/dist/services/codex-subagent-hook-template.d.ts +1 -1
  51. package/dist/services/codex-subagent-hook-template.d.ts.map +1 -1
  52. package/dist/services/codex-subagent-hook-template.js +59 -15
  53. package/dist/services/codex-subagent-hook-template.js.map +1 -1
  54. package/dist/services/codex-validation-runtime-template.d.ts.map +1 -1
  55. package/dist/services/codex-validation-runtime-template.js +37 -10
  56. package/dist/services/codex-validation-runtime-template.js.map +1 -1
  57. package/dist/services/runtime-template-test-support.d.ts +1 -0
  58. package/dist/services/runtime-template-test-support.d.ts.map +1 -1
  59. package/dist/services/runtime-template-test-support.js +23 -2
  60. package/dist/services/runtime-template-test-support.js.map +1 -1
  61. package/dist/services/runtime-template.test.js +7 -24
  62. package/dist/services/runtime-template.test.js.map +1 -1
  63. package/package.json +1 -1
  64. package/templates/.agents/README-ENG.md +49 -7
  65. package/templates/.agents/README.md +41 -10
  66. package/templates/.agents/config/agents/discovery.json +1 -1
  67. package/templates/.agents/dashboard/.zaip-managed.json +125 -73
  68. package/templates/.agents/dashboard/apps/frontend/dist/assets/{CostCalculationGuidePage-BW7Vy1cp.js → CostCalculationGuidePage-w6pjt4OM.js} +1 -1
  69. package/templates/.agents/dashboard/apps/frontend/dist/assets/{DashboardHelpDialog-BN8KQPrr.js → DashboardHelpDialog-DhlntQcR.js} +117 -17
  70. package/templates/.agents/dashboard/apps/frontend/dist/assets/{PricingSettingsDialog-Prcs-ydy.js → PricingSettingsDialog-BHoZT2an.js} +1 -1
  71. package/templates/.agents/dashboard/apps/frontend/dist/assets/{ProjectSettingsPage-HqGUImIG.js → ProjectSettingsPage-IcncIZ9Y.js} +1 -1
  72. package/templates/.agents/dashboard/apps/frontend/dist/assets/{TraceabilityWorkspace-CNpmQMO4.js → TraceabilityWorkspace-C6rORjpr.js} +1 -1
  73. package/templates/.agents/dashboard/apps/frontend/dist/assets/cost-monitor-uPnOBShc.js +68 -0
  74. package/templates/.agents/dashboard/apps/frontend/dist/assets/{dashboard-localization-CF7B1Hjn.js → dashboard-localization-DWXjEIgc.js} +49 -7
  75. package/templates/.agents/dashboard/apps/frontend/dist/assets/{icons-vendor-DOhy6D2-.js → icons-vendor-Hc9fp_gs.js} +1 -1
  76. package/templates/.agents/dashboard/apps/frontend/dist/assets/{index-DX65Ufuu.js → index-BqeOEZW5.js} +2 -2
  77. package/templates/.agents/dashboard/apps/frontend/dist/assets/{react-vendor-CkPC-yMz.js → react-vendor-C9ta_O10.js} +1 -1
  78. package/templates/.agents/dashboard/apps/frontend/dist/assets/{traceability-BEdGoIDm.js → traceability-IcefoTOv.js} +1 -1
  79. package/templates/.agents/dashboard/apps/frontend/dist/index.html +5 -5
  80. package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
  81. package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
  82. package/templates/.agents/dashboard/modules/cost-monitor/src/contracts.ts +10 -3
  83. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostFilters.run-page.test.ts +5 -1
  84. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostGroupsTable.period-values.test.tsx +2 -2
  85. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostTables-keeps-legacy-codex-identity-fields-blank.test.ts +5 -5
  86. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostTables.test.ts +36 -43
  87. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-loaders.ts +1 -0
  88. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-table-formatters.ts +6 -4
  89. package/templates/.agents/dashboard/modules/cost-monitor/src/server/aggregate.ts +2 -2
  90. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-monitor-projection.ts +1 -1
  91. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-summary-projection.ts +11 -25
  92. package/templates/.agents/dashboard/modules/cost-monitor/src/server/cost-summary-defaults.ts +26 -0
  93. package/templates/.agents/dashboard/modules/operations/package.json +1 -1
  94. package/templates/.agents/dashboard/modules/operations/src/contracts.ts +11 -16
  95. package/templates/.agents/dashboard/modules/operations/src/planning-contracts.ts +14 -0
  96. package/templates/.agents/dashboard/modules/operations/src/react/DecisionTable.tsx +65 -0
  97. package/templates/.agents/dashboard/modules/operations/src/react/EntityTables.tsx +5 -71
  98. package/templates/.agents/dashboard/modules/operations/src/react/OperationsPage.tsx +10 -36
  99. package/templates/.agents/dashboard/modules/operations/src/react/operations-overview-period-filter.test.ts +7 -2
  100. package/templates/.agents/dashboard/modules/operations/src/react/use-operations-filter-sync.ts +66 -0
  101. package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
  102. package/templates/.agents/dashboard/packages/branding/package.json +1 -1
  103. package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
  104. package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
  105. package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +229 -222
  106. package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +167 -167
  107. package/templates/.agents/dashboard/packages/local-runtime/package.json +3 -3
  108. package/templates/.agents/dashboard/packages/local-runtime/server.mjs +229 -222
  109. package/templates/.agents/dashboard/packages/local-runtime/src/active-capture-failure.test.ts +38 -0
  110. package/templates/.agents/dashboard/packages/local-runtime/src/active-capture-failure.ts +35 -0
  111. package/templates/.agents/dashboard/packages/local-runtime/src/active-codex-telemetry.test.ts +69 -6
  112. package/templates/.agents/dashboard/packages/local-runtime/src/active-codex-telemetry.ts +62 -15
  113. package/templates/.agents/dashboard/packages/local-runtime/src/manifest-runs.ts +8 -2
  114. package/templates/.agents/dashboard/packages/local-runtime/src/server-capture-projection-order.test.ts +118 -0
  115. package/templates/.agents/dashboard/packages/local-runtime/src/server-cost-run-search.test.ts +90 -0
  116. package/templates/.agents/dashboard/packages/local-runtime/src/server-cost-run-search.ts +86 -0
  117. package/templates/.agents/dashboard/packages/local-runtime/src/server-operations-routes.ts +8 -1
  118. package/templates/.agents/dashboard/packages/local-runtime/src/server-projection-loaders.ts +13 -0
  119. package/templates/.agents/dashboard/packages/local-runtime/src/server-projections.ts +30 -74
  120. package/templates/.agents/dashboard/packages/local-runtime/src/server-route-handlers.ts +42 -0
  121. package/templates/.agents/dashboard/packages/local-runtime/src/server-routes.test.ts +60 -0
  122. package/templates/.agents/dashboard/packages/local-runtime/src/server-run-projections.test.ts +12 -2
  123. package/templates/.agents/dashboard/packages/local-runtime/src/server-telemetry-command.test.ts +29 -4
  124. package/templates/.agents/dashboard/packages/local-runtime/src/server-telemetry-refresh.ts +7 -0
  125. package/templates/.agents/dashboard/packages/local-runtime/src/server.test.ts +51 -54
  126. package/templates/.agents/dashboard/packages/local-runtime/src/server.ts +37 -48
  127. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-cost-filter-matrix.test.ts +5 -0
  128. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-cost-invocation-page.test.ts +49 -0
  129. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-cost-invocation-page.ts +44 -1
  130. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-cached-cost-page.ts +11 -10
  131. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-summary.ts +1 -1
  132. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-work-item-index.test.ts +18 -1
  133. package/templates/.agents/dashboard/packages/local-runtime/vitest.config.ts +12 -0
  134. package/templates/.agents/dashboard/packages/ui/package.json +1 -1
  135. package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
  136. package/templates/.agents/dashboard/tests/e2e/specs/cost-monitor-pagination.spec.ts +13 -6
  137. package/templates/.agents/dashboard/tests/e2e/specs/dashboard.spec.ts +1 -1
  138. package/templates/.agents/design/.zaip-managed.json +3 -3
  139. package/templates/.agents/design/apps/catalog/package.json +1 -1
  140. package/templates/.agents/design/packages/local-runtime/package.json +1 -1
  141. package/templates/.agents/requirements/autonomous-assurance.md +39 -3
  142. package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
  143. package/templates/.agents/requirements/comparative-audit.md +1 -1
  144. package/templates/.agents/requirements/context-engine.md +3 -3
  145. package/templates/.agents/requirements/cost-observability.md +1 -1
  146. package/templates/.agents/requirements/dashboard-launch.md +1 -1
  147. package/templates/.agents/requirements/data-export.md +1 -1
  148. package/templates/.agents/requirements/design-system.md +1 -1
  149. package/templates/.agents/requirements/execution-engine.md +11 -2
  150. package/templates/.agents/requirements/kanban-dashboard.md +1 -1
  151. package/templates/.agents/requirements/model-orchestration.md +1 -1
  152. package/templates/.agents/requirements/public-distribution.md +1 -1
  153. package/templates/.agents/requirements/software-architecture.md +1 -1
  154. package/templates/.agents/requirements/strategic-improvements.md +1 -1
  155. package/templates/.agents/requirements/work-lifecycle.md +2 -1
  156. package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
  157. package/templates/.agents/rules/cloud-hostinger-autonomy.md +1 -1
  158. package/templates/.agents/rules/production-readiness.md +24 -0
  159. package/templates/.agents/rules/run-lifecycle-closure.md +2 -1
  160. package/templates/.agents/rules/security.md +2 -2
  161. package/templates/.agents/rules/workflow.md +4 -3
  162. package/templates/.agents/runtime/VERSION +1 -1
  163. package/templates/.agents/runtime/bin/zaip.mjs +1185 -610
  164. package/templates/.agents/runtime/checksums.sha256 +6 -6
  165. package/templates/.agents/runtime/manifest.json +1 -1
  166. package/templates/.agents/runtime/pnpm-lock.sha256 +1 -1
  167. package/templates/.agents/runtime/provenance.json +5 -5
  168. package/templates/.agents/runtime/sbom.cdx.json +71 -71
  169. package/templates/.agents/skills/zaip-skill-execution/SKILL.md +4 -2
  170. package/templates/.agents/skills/zaip-skill-execution/references/controlled-release-recovery.md +44 -0
  171. package/templates/.agents/skills/zaip-skill-execution/references/runtime-governance.md +1 -1
  172. package/templates/.agents/skills/zaip-skill-github-deploy/SKILL.md +7 -1
  173. package/templates/.agents/skills/zaip-skill-github-deploy/references/release-gate-matrix.md +15 -20
  174. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-contract.mjs +38 -2
  175. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-contract.test.mjs +62 -4
  176. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-deploy-contract.test.mjs +8 -6
  177. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/guarded-commits.mjs +5 -3
  178. package/templates/.agents/skills/zaip-skill-lifecycle-closure/SKILL.md +7 -0
  179. package/templates/.agents/skills/zaip-skill-maintenance-enter/SKILL.md +23 -0
  180. package/templates/.agents/skills/zaip-skill-maintenance-enter/agents/openai.yaml +4 -0
  181. package/templates/.agents/skills/zaip-skill-maintenance-enter/scripts/maintenance.mjs +213 -0
  182. package/templates/.agents/skills/zaip-skill-maintenance-enter/scripts/maintenance.test.mjs +207 -0
  183. package/templates/.agents/skills/zaip-skill-maintenance-exit/SKILL.md +21 -0
  184. package/templates/.agents/skills/zaip-skill-maintenance-exit/agents/openai.yaml +4 -0
  185. package/templates/.agents/skills/zaip-skill-prd/SKILL.md +6 -0
  186. package/templates/.agents/skills/zaip-skill-release-qualification/SKILL.md +26 -0
  187. package/templates/.agents/skills/zaip-skill-release-qualification/references/local-preparation.md +46 -11
  188. package/templates/.agents/skills/zaip-skill-spec/SKILL.md +9 -0
  189. package/templates/.agents/skills/zaip-skill-testing-strategy/SKILL.md +15 -0
  190. package/templates/.agents/zaip-aios/VERSION +1 -1
  191. package/templates/.agents/zaip-aios/guides/11-observabilidade-e-custos.md +22 -0
  192. package/templates/.agents/zaip-aios/guides/14-troubleshooting.md +1 -1
  193. package/templates/.agents/zaip-aios/guides/26-qualidade-e-release.md +52 -5
  194. package/templates/template-manifest.json +210 -126
  195. package/templates/.agents/dashboard/apps/frontend/dist/assets/cost-monitor-Co2Jiuzh.js +0 -68
@@ -8,11 +8,11 @@ English | [Português](README.md)
8
8
 
9
9
  ## Quick overview
10
10
 
11
- > **Approved v4 target, not a shipped guarantee:** the Codex-native intake,
12
- > subagent, scheduling, replanning, closure, and numeric display rules below
13
- > still require implementation and qualification in the exact candidate and
14
- > installed npm package. The [v4 lifecycle guide](.agents/zaip-aios/guides/28-lifecycle-completo.md#contrato-aprovado-para-a-v4-a-implementar-e-qualificar)
15
- > distinguishes this target from current behavior and lists observable gates.
11
+ > **Source, candidate, and publication:** this README describes the checkout's
12
+ > contracts and features. The [evolution matrix](docs/quality/v50-documentacao-editorial.md)
13
+ > identifies implementation and evidence. Local qualification, consumer hook
14
+ > activation, GitHub Release, and npm require separate verification; documenting
15
+ > a contract does not replace observation in the installed package.
16
16
 
17
17
  The [Codex-native compatibility contract](.agents/zaip-aios/guides/28-lifecycle-completo.md#fronteiras-nativas-e-prova-de-compatibilidade)
18
18
  separates subagents, hooks, scheduling, and installer requirements. An abrupt
@@ -70,7 +70,31 @@ This README and the [handbook](.agents/zaip-aios/INDEX.md) describe this reposit
70
70
 
71
71
  Documentation changes do not approve a release. Consult the [qualification-limits record](docs/PRODUCTION-COMMERCIAL-READINESS.md#limites-conhecidos-da-qualificação) before promoting code; local tests, parity, CI, and production validation must be proven separately.
72
72
 
73
- For v3 delivery, the complete suite runs in signed local preparation (\`full-v2\`). GitHub verifies the exact package, installation and publication without repeating source tests on every push. Activation requires full local qualification and enrolled trust. One automatic installation smoke precedes npm publication; source checks and the remote matrix are manual, with no private-draft pilot. See the [quality and release guide](.agents/zaip-aios/guides/26-qualidade-e-release.md). Historical telemetry gaps remain explicit, without invented values or waived tests for new data.
73
+ Signed local preparation defaults to \`essential-v3\`; \`full-v2\` is an explicitly selected extended qualification. Lint and generated-text normalization run before the build; canonical changes are checked after every gate with the stage and affected paths in the diagnostic. After local checks, pushing to \`main\` triggers \`pre-main-candidate.yml\` for integrity, lint, types, commit identity, and impact-selected regressions. Release requires successful CI on the exact SHA. The publisher verifies signed artifacts, runs a Linux package smoke before npm publication, and confirms registry integrity; extended post-publication installation is optional. See the [quality and release guide](.agents/zaip-aios/guides/26-qualidade-e-release.md). Historical telemetry gaps stay explicit, without invented values or waived tests for new data.
74
+
75
+ Before freezing the candidate, synchronize the tracked runtime, server, and bundles as well. Qualification rejects drift in these files after each gate. In pre-main, the public group prepares and checks distribution before other tests while preserving selection, authenticated caching, and failure recording; generated outputs remain subject to the clean-checkout requirement.
76
+
77
+ Published history includes [Release v4.9](https://github.com/zaip-ai/zaip-aios/releases/tag/v4.9). Later changes are identified in the [evolution matrix](docs/quality/v50-documentacao-editorial.md); they do not retroactively change the published package.
78
+
79
+ ### Reliability, efficiency, and maintenance
80
+
81
+ The 5.0 line brings together causal recovery and [resumable delivery](docs/quality/v50-deploy-retomavel.md) with [preflight and rework prevention](docs/quality/v50-retrabalho-e-publicacao.md),
82
+ risk-based tests, authenticated caching, batched telemetry with deduplication,
83
+ and proportional editorial review. The [native consumer pilot](docs/quality/v50-consumidor-nativo.md)
84
+ observed all four hooks on Windows and fixed Stop replay to preserve the final
85
+ decision summary. The [documentation matrix](docs/quality/v50-documentacao-editorial.md)
86
+ maps all ten work areas to their evidence; each publication still requires the
87
+ exact TGZ, main CI, signed artifacts, and npm integrity.
88
+
89
+ Execution uses preflight before materializing work, recovery with exact identity and review, checkpoints to avoid repetition, and tests selected by impact. Validation batches share preparation for the same candidate; authenticated cache reuse requires trusted authority, a valid signature, and matching identity. A local cache does not imply an approved HIT or measured savings.
90
+
91
+ Creating a SPEC in \`draft\` persists its definition and blueprints without delivery Tasks. \`ready\` materializes the DAG with \`planned\` Tasks; \`execute\` starts the smallest authorized unit. Ten blueprints describe ten planned pieces of work, but do not prove that ten Tasks have started or completed.
92
+
93
+ An explicitly editorial \`lite\` Task may use \`README.md\`, \`README-ENG.md\`, or Markdown in a narrow \`docs/\` scope such as \`docs/quality/**\`. It still requires a candidate, check, Evidence, review, and finalizer. Code, configuration, agent controls, sensitive data, and \`standard\`/\`critical\` risk retain the full process. The broad \`docs/**\` scope does not grant this exception.
94
+
95
+ The \`zaip-aios-full-access\` profile permits configured external read, write, execution, working-directory, and network access. Secret, destructive-operation, lifecycle-authority, restricted-subagent, and computer power/session protections remain. Explicitly authorized maintenance uses \`node .agents/skills/zaip-skill-maintenance-enter/scripts/maintenance.mjs enter\`; reactivate with the same script and \`exit\`. Tracking remains enabled; configuration alone does not prove the four native hook events.
96
+
97
+ See the [change, command, evidence, and limitation matrix](docs/quality/v50-documentacao-editorial.md) and [operations runbook](docs/quality/v50-task10-operations-runbook.md). No general 30% speed gain has been demonstrated: the local 160-sample comparison preserved integrity, but intake p95 with three writers increased by 18.6%. Final production assessment depends on the consumer and publication of the exact candidate.
74
98
 
75
99
  ## One-command installation
76
100
 
@@ -851,7 +875,13 @@ Both profiles retain compensating layers that reduce risk, but do not replace th
851
875
  - subagents with bounded responsibilities and scopes, plus hashed adapters, framework lock, and regression gates;
852
876
  - remaining operating-system controls, such as ACLs, account privileges, and host policies.
853
877
 
854
- The \`PreToolUse\` security hook also remains active in the full-access profile without reducing its native permissions; it blocks destructive classes, secrets, publication, and elevation without authorization. Subagent lifecycle hooks remain active for defense in depth and attribution/telemetry. Browser, Computer Use, MCPs, and other integrations have their own surfaces and should be enabled and used only when necessary. For strong isolation against scope errors or malicious code, use the restricted profile and, when the risk warrants it, a dedicated account, VM, or external network and filesystem controls.
878
+ With \`zaip.enabled: true\`, the \`PreToolUse\` security hook also remains active in the full-access profile without reducing its native permissions; it blocks destructive classes, secrets, publication, and elevation without authorization. Subagent lifecycle hooks remain active for defense in depth and attribution/telemetry. Browser, Computer Use, MCPs, and other integrations have their own surfaces and should be enabled and used only when necessary. For strong isolation against scope errors or malicious code, use the restricted profile and, when the risk warrants it, a dedicated account, VM, or external network and filesystem controls.
879
+
880
+ The four events (\`PreToolUse\`, \`SubagentStart\`, \`SubagentStop\`, and \`Stop\`) use independent controls in \`.agents/config/project.yaml\`: \`zaip.enabled\` controls ZAIP rules, while \`tracking.enabled\` controls telemetry collection. With ZAIP disabled and tracking enabled, observation continues without requiring a Task, Execution, or finalizer. Disabling tracking preserves existing records. Configuration is read again on the next invocation; a hook disabled in the Codex interface must be enabled there to execute. See the [control contract and validation matrix](docs/quality/hook-independent-controls.md).
881
+
882
+ PreToolUse evaluates filesystem and network separately from the configured profile. The full-access principal can use canonical external paths; writes retain authority and writer-claim requirements, and subagents retain their restrictions. Recovery of observed failures is evaluated before finalizer delegation, preserving unknown history as unavailable. See the [path and recovery contract](docs/quality/hook-full-access-paths.md).
883
+
884
+ For authorized maintenance, use [$zaip-skill-maintenance-enter](.agents/skills/zaip-skill-maintenance-enter/SKILL.md), then [$zaip-skill-maintenance-exit](.agents/skills/zaip-skill-maintenance-exit/SKILL.md). These skills change only the controls, keep tracking enabled, and preserve configuration edits made during the work. The toggle applies to the whole project; coordinate concurrent chats. Exit reactivates ZAIP and requires a real invocation to verify the hook and canonical observation.
855
885
 
856
886
  The [complete ZAIP-AIOS permission-profile security guide](.agents/zaip-aios/guides/10-seguranca.md) documents the threat model, allow/deny matrix, layers, limitations, safe operation, rollout, rollback, and validation commands.
857
887
 
@@ -882,4 +912,16 @@ node .agents/skills/criar-pasta-obsidian/scripts/generate-obsidian-vault.mjs
882
912
  \`\`\`
883
913
 
884
914
  The [ZAIP traceability Obsidian guide](guide/CRIAR-PASTA-OBSIDIAN.md) documents application installation, opening the folder as a vault, generating a single Task, and updating the projection after \`git pull\`.
915
+
916
+ ## Branches, worktrees, and the current release
917
+
918
+ Candidate validation uses a detached checkout outside the repository, under the
919
+ system temporary directory with prefix \`zaip-candidate-<project>-\`. Cleanup
920
+ verifies ownership and preserves the working checkout.
921
+
922
+ A branch holds a commit history; a worktree is another checkout directory. A standalone Task or serial PRD/SPEC uses the shared checkout claimed by \`zaip task workspace\`, without requiring either. Eligible independent parallel work receives an isolated checkout. Closing an isolated front preserves verified local backups and snapshots under \`.local/backup-branchs\` and \`.local/backup-worktrees\`, tests restoration, then closes the branch/worktree. Unattributed shared changes or invalid backups block cleanup until reconciliation. Backups are Git-ignored; their deletion is manual.
923
+
924
+ \`.agents/config/release-cycle.json\` defines the executable release. Future PRDs/SPECs may remain draft; starting requires the current cycle. Publication reconciles active work, freezes and audits the exact candidate, runs local checks, pushes only \`main\`, and waits for successful CI on that SHA before Release. No remote candidate branch is created. Tag, GitHub Release, npm, and any applicable provider deployment have separate evidence.
925
+
926
+ The release coordinator may remain active during publication and cycle advance only through supported modes: an integrated root with explicit frozen IDs and \`release_mode: integrated_task\`, or delegated SPEC coordination with verified ancestry. Other current Tasks must be terminal. The gate verifies candidate records; the coordinator completes Evidence, applicable review, and Gui after publication proof. Simple coordination must finish before audit. See the [release contracts and commands](.agents/zaip-aios/guides/26-qualidade-e-release.md#ciclo-corrente-limpeza-e-ci-da-main-antes-da-release). Do not mark a Task completed before its finalizer just to publish.
885
927
  `:n},...i]}function t(e,t){return e.match(/^#\s+(.+)$/m)?.[1]?.trim()??t.replace(/\.md$/i,``)}var n={"pt-BR":{eyebrow:`CONFIGURAÇÃO DO PROJETO`,title:`Preços e cotação`,description:`Valores em USD por 1 milhão de tokens. Ao salvar, o dashboard recalcula todos os valores com o catálogo vigente.`,back:`Voltar ao dashboard`,fxTitle:`Cotação utilizada no dashboard`,fxDescription:`Ao salvar, todos os valores em BRL são recalculados. Os valores em USD e a telemetria de tokens permanecem inalterados.`,fxLabel:`Cotação USD/BRL`,fxAriaLabel:`Cotação USD BRL`,catalog:`Catálogo de modelos`,pricesPerMillion:`Preços em USD por 1 milhão de tokens`,models:`modelos`,model:`Modelo`,provider:`Provider`,input:`Entrada (USD/1M)`,cache:`Cache (USD/1M)`,output:`Saída (USD/1M)`,reasoning:`Raciocínio (USD/1M)`,priorityInput:`Priority entrada (USD/1M)`,priorityCache:`Priority cache (USD/1M)`,priorityOutput:`Priority saída (USD/1M)`,priorityReasoning:`Priority raciocínio (USD/1M)`,contextLimit:`Limite contexto`,inputMultiplier:`Mult. entrada`,outputMultiplier:`Mult. saída`,noAliases:`sem aliases`,removeModel:`Remover modelo`,addModel:`Adicionar modelo`,cancel:`Cancelar`,saving:`Salvando…`,save:`Salvar e recalcular`,newModel:`novo-modelo`,manualOverride:`Substituição manual pelo dashboard`,editedNote:`Editado no dashboard`},"en-US":{eyebrow:`PROJECT SETTINGS`,title:`Pricing and exchange rate`,description:`Prices in USD per 1 million tokens. When saved, the dashboard recalculates all values using the current catalog.`,back:`Back to dashboard`,fxTitle:`Exchange rate used by the dashboard`,fxDescription:`When saved, all BRL values are recalculated. USD values and token telemetry remain unchanged.`,fxLabel:`USD/BRL exchange rate`,fxAriaLabel:`USD BRL exchange rate`,catalog:`Model catalog`,pricesPerMillion:`Prices in USD per 1 million tokens`,models:`models`,model:`Model`,provider:`Provider`,input:`Input (USD/1M)`,cache:`Cache (USD/1M)`,output:`Output (USD/1M)`,reasoning:`Reasoning (USD/1M)`,priorityInput:`Priority input (USD/1M)`,priorityCache:`Priority cache (USD/1M)`,priorityOutput:`Priority output (USD/1M)`,priorityReasoning:`Priority reasoning (USD/1M)`,contextLimit:`Context limit`,inputMultiplier:`Input multiplier`,outputMultiplier:`Output multiplier`,noAliases:`no aliases`,removeModel:`Remove model`,addModel:`Add model`,cancel:`Cancel`,saving:`Saving…`,save:`Save and recalculate`,newModel:`new-model`,manualOverride:`Dashboard manual override`,editedNote:`Edited in dashboard`}};export{n,e as t};
@@ -1 +1 @@
1
- import{h as e}from"./cost-monitor-Co2Jiuzh.js";var t=e(`BadgeCheck`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),n=e(`CalendarDays`,[[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`4`,rx:`2`,key:`1hopcy`}],[`path`,{d:`M3 10h18`,key:`8toen8`}],[`path`,{d:`M8 14h.01`,key:`6423bh`}],[`path`,{d:`M12 14h.01`,key:`1etili`}],[`path`,{d:`M16 14h.01`,key:`1gbofw`}],[`path`,{d:`M8 18h.01`,key:`lrp35t`}],[`path`,{d:`M12 18h.01`,key:`mhygvu`}],[`path`,{d:`M16 18h.01`,key:`kzsmim`}]]),r=e(`Check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),i=e(`CircleGauge`,[[`path`,{d:`M15.6 2.7a10 10 0 1 0 5.7 5.7`,key:`1e0p6d`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}],[`path`,{d:`M13.4 10.6 19 5`,key:`1kr7tw`}]]),a=e(`ClipboardList`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`M12 11h4`,key:`1jrz19`}],[`path`,{d:`M12 16h4`,key:`n85exb`}],[`path`,{d:`M8 11h.01`,key:`1dfujw`}],[`path`,{d:`M8 16h.01`,key:`18s6g9`}]]),o=e(`Copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),s=e(`FileCheck2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`m3 15 2 2 4-4`,key:`1lhrkk`}]]),c=e(`FileStack`,[[`path`,{d:`M21 7h-3a2 2 0 0 1-2-2V2`,key:`9rb54x`}],[`path`,{d:`M21 6v6.5c0 .8-.7 1.5-1.5 1.5h-7c-.8 0-1.5-.7-1.5-1.5v-9c0-.8.7-1.5 1.5-1.5H17Z`,key:`1059l0`}],[`path`,{d:`M7 8v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H15`,key:`16874u`}],[`path`,{d:`M3 12v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H11`,key:`k2ox98`}]]),l=e(`Gavel`,[[`path`,{d:`m14.5 12.5-8 8a2.119 2.119 0 1 1-3-3l8-8`,key:`15492f`}],[`path`,{d:`m16 16 6-6`,key:`vzrcl6`}],[`path`,{d:`m8 8 6-6`,key:`18bi4p`}],[`path`,{d:`m9 7 8 8`,key:`5jnvq1`}],[`path`,{d:`m21 11-8-8`,key:`z4y7zo`}]]),u=e(`LayoutGrid`,[[`rect`,{width:`7`,height:`7`,x:`3`,y:`3`,rx:`1`,key:`1g98yp`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`14`,rx:`1`,key:`nxv5o0`}],[`rect`,{width:`7`,height:`7`,x:`3`,y:`14`,rx:`1`,key:`1bb6yr`}]]),d=e(`Link2`,[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]),f=e(`Settings`,[[`path`,{d:`M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z`,key:`1qme2f`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),p=e(`ShieldCheck`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),m=e(`Workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]);export{u as a,s as c,i as d,r as f,d as i,o as l,t as m,p as n,l as o,n as p,f as r,c as s,m as t,a as u};
1
+ import{h as e}from"./cost-monitor-uPnOBShc.js";var t=e(`BadgeCheck`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),n=e(`CalendarDays`,[[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`4`,rx:`2`,key:`1hopcy`}],[`path`,{d:`M3 10h18`,key:`8toen8`}],[`path`,{d:`M8 14h.01`,key:`6423bh`}],[`path`,{d:`M12 14h.01`,key:`1etili`}],[`path`,{d:`M16 14h.01`,key:`1gbofw`}],[`path`,{d:`M8 18h.01`,key:`lrp35t`}],[`path`,{d:`M12 18h.01`,key:`mhygvu`}],[`path`,{d:`M16 18h.01`,key:`kzsmim`}]]),r=e(`Check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),i=e(`CircleGauge`,[[`path`,{d:`M15.6 2.7a10 10 0 1 0 5.7 5.7`,key:`1e0p6d`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}],[`path`,{d:`M13.4 10.6 19 5`,key:`1kr7tw`}]]),a=e(`ClipboardList`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`M12 11h4`,key:`1jrz19`}],[`path`,{d:`M12 16h4`,key:`n85exb`}],[`path`,{d:`M8 11h.01`,key:`1dfujw`}],[`path`,{d:`M8 16h.01`,key:`18s6g9`}]]),o=e(`Copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),s=e(`FileCheck2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`m3 15 2 2 4-4`,key:`1lhrkk`}]]),c=e(`FileStack`,[[`path`,{d:`M21 7h-3a2 2 0 0 1-2-2V2`,key:`9rb54x`}],[`path`,{d:`M21 6v6.5c0 .8-.7 1.5-1.5 1.5h-7c-.8 0-1.5-.7-1.5-1.5v-9c0-.8.7-1.5 1.5-1.5H17Z`,key:`1059l0`}],[`path`,{d:`M7 8v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H15`,key:`16874u`}],[`path`,{d:`M3 12v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H11`,key:`k2ox98`}]]),l=e(`Gavel`,[[`path`,{d:`m14.5 12.5-8 8a2.119 2.119 0 1 1-3-3l8-8`,key:`15492f`}],[`path`,{d:`m16 16 6-6`,key:`vzrcl6`}],[`path`,{d:`m8 8 6-6`,key:`18bi4p`}],[`path`,{d:`m9 7 8 8`,key:`5jnvq1`}],[`path`,{d:`m21 11-8-8`,key:`z4y7zo`}]]),u=e(`LayoutGrid`,[[`rect`,{width:`7`,height:`7`,x:`3`,y:`3`,rx:`1`,key:`1g98yp`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`14`,rx:`1`,key:`nxv5o0`}],[`rect`,{width:`7`,height:`7`,x:`3`,y:`14`,rx:`1`,key:`1bb6yr`}]]),d=e(`Link2`,[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]),f=e(`Settings`,[[`path`,{d:`M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z`,key:`1qme2f`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),p=e(`ShieldCheck`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),m=e(`Workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]);export{u as a,s as c,i as d,r as f,d as i,o as l,t as m,p as n,l as o,n as p,f as r,c as s,m as t,a as u};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DashboardHelpDialog-BN8KQPrr.js","assets/rolldown-runtime-Bh1tDfsg.js","assets/cost-monitor-Co2Jiuzh.js","assets/cost-monitor-C2AFYBu_.css","assets/dashboard-localization-CF7B1Hjn.js","assets/DashboardHelpDialog-DRI_XwUf.css","assets/PricingSettingsDialog-Prcs-ydy.js","assets/ProjectSettingsPage-HqGUImIG.js","assets/ProjectSettingsPage-CQMhvzvJ.css","assets/CostCalculationGuidePage-BW7Vy1cp.js","assets/TraceabilityWorkspace-CNpmQMO4.js","assets/traceability-BEdGoIDm.js","assets/icons-vendor-DOhy6D2-.js","assets/traceability-DFY7ZDlu.css","assets/TraceabilityWorkspace-DvvavDLY.css"])))=>i.map(i=>d[i]);
2
- import{n as e}from"./rolldown-runtime-Bh1tDfsg.js";import{E as t,a as n,b as r,g as i,i as a,n as o,o as s,r as c,t as l,w as u}from"./cost-monitor-Co2Jiuzh.js";import{t as d}from"./react-vendor-CkPC-yMz.js";import{n as f,t as p}from"./traceability-BEdGoIDm.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var m=e(t(),1),h=d(),g=u();function _({locale:e}){let t=e===`pt-BR`?[`Definição`,`Planejamento`,`Pronto para Executar`,`Execução`,`Verificação`]:[`Definition`,`Planning`,`Ready to Execute`,`Execution`,`Verification`];return(0,g.jsxs)(`main`,{"aria-busy":`true`,"aria-live":`polite`,"aria-label":e===`pt-BR`?`Preparando dashboard`:`Preparing dashboard`,className:`app-skeleton`,role:`status`,children:[(0,g.jsxs)(`header`,{className:`app-skeleton-header`,children:[(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-short`}),(0,g.jsx)(`h1`,{children:`Dashboard ZAIP AIOS`})]}),(0,g.jsxs)(`div`,{className:`app-skeleton-actions`,children:[(0,g.jsx)(`span`,{}),(0,g.jsx)(`span`,{}),(0,g.jsx)(`span`,{})]})]}),(0,g.jsx)(`section`,{className:`app-skeleton-kpis`,"aria-hidden":`true`,children:Array.from({length:4},(e,t)=>`skeleton-kpi-${t}`).map(e=>(0,g.jsxs)(`article`,{children:[(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-short`}),(0,g.jsx)(`span`,{className:`app-skeleton-value`}),(0,g.jsx)(`span`,{className:`app-skeleton-line`})]},e))}),(0,g.jsxs)(`section`,{className:`app-skeleton-panels`,"aria-hidden":`true`,children:[(0,g.jsxs)(`article`,{children:[(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-medium`}),(0,g.jsx)(`div`,{className:`app-skeleton-chart`})]}),(0,g.jsxs)(`article`,{children:[(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-medium`}),(0,g.jsx)(`div`,{className:`app-skeleton-chart app-skeleton-chart-small`})]})]}),(0,g.jsx)(`section`,{className:`app-skeleton-board`,"aria-hidden":`true`,children:t.map((e,t)=>(0,g.jsxs)(`article`,{children:[(0,g.jsx)(`h2`,{children:e}),Array.from({length:t%2==0?2:1},(t,n)=>`${e}-${n}`).map(e=>(0,g.jsxs)(`div`,{className:`app-skeleton-card`,children:[(0,g.jsx)(`span`,{className:`app-skeleton-line`}),(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-medium`}),(0,g.jsx)(`span`,{className:`app-skeleton-pill`})]},e))]},e))})]})}function v(e,t){let n=t===`pt-BR`;return e===`costs`?n?{title:`Carregando Monitor de Custos…`,detail:`Isso costuma levar poucos segundos.`}:{title:`Loading Cost Monitor…`,detail:`This usually takes a few seconds.`}:e===`traceability`?n?{title:`Carregando Rastreabilidade…`,detail:`Estamos preparando as 6 etapas da task.`}:{title:`Loading Traceability…`,detail:`Preparing the task's 6 stages.`}:n?{title:`Atualizando dados do dashboard…`,detail:`Você pode continuar navegando.`}:{title:`Refreshing dashboard data…`,detail:`You can keep navigating.`}}function y({area:e,locale:t}){let n=v(e,t);return(0,g.jsxs)(`section`,{"aria-busy":`true`,"aria-live":`polite`,className:`app-loading-panel`,role:`status`,children:[(0,g.jsx)(`i`,{}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`strong`,{children:n.title}),(0,g.jsx)(`span`,{children:n.detail})]})]})}function b({area:e,locale:t}){let n=v(e,t);return(0,g.jsxs)(`section`,{"aria-live":`polite`,className:`app-refresh-status`,role:`status`,children:[(0,g.jsx)(`i`,{}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`strong`,{children:n.title}),(0,g.jsx)(`span`,{children:n.detail})]})]})}function x({locale:e,onRetry:t}){return(0,g.jsxs)(`section`,{"aria-live":`polite`,className:`app-loading-panel app-loading-panel-error`,role:`status`,children:[(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`strong`,{children:e===`pt-BR`?`Não foi possível carregar os custos`:`Couldn't load costs`}),(0,g.jsx)(`span`,{children:e===`pt-BR`?`A tela continua disponível. Tente novamente quando quiser.`:`The dashboard remains available. Try again whenever you want.`})]}),(0,g.jsx)(`button`,{onClick:t,type:`button`,children:e===`pt-BR`?`Tentar novamente`:`Try again`})]})}function S({costsLoaded:e,currency:t,snapshotCurrency:n}){return!e||n!==t}function C({aborted:e,currentCurrency:t,currentPeriod:n,currentRequestVersion:r,requestVersion:i,requestedCurrency:a,requestedPeriod:o}){return!e&&i===r&&a===t&&o.from===n.from&&o.to===n.to}function w(e,t){return e===t}function T(e,t,n,r){return w(e,t)&&n.from===r.from&&n.to===r.to}function E(e){return e instanceof DOMException&&e.name===`AbortError`}function D(e,t){return e===t}function O(e,t,n){return w(e,t)&&!n.aborted}function k(e,t){let n=e=>[...new Map(e.map(e=>[e.id,e])).values()];return{...e,prds:n([...e.prds,...t.flatMap(e=>e.prds)]),specs:n([...e.specs,...t.flatMap(e=>e.specs)]),tasks:n([...e.tasks,...t.flatMap(e=>e.tasks)]),changes:n([...e.changes,...t.flatMap(e=>e.changes)])}}function ee(){let e=(0,m.useRef)(null);return(0,m.useEffect)(()=>{e.current?.focus()},[]),(0,g.jsx)(`div`,{"aria-busy":`true`,"aria-live":`polite`,className:`period-transition-overlay`,onKeyDownCapture:e=>e.preventDefault(),ref:e,role:`status`,tabIndex:-1,children:(0,g.jsxs)(`div`,{className:`period-transition-overlay__content`,children:[(0,g.jsx)(`i`,{"aria-hidden":`true`,className:`period-transition-overlay__spinner`}),(0,g.jsx)(`span`,{className:`period-transition-overlay__label`,children:`Carregando...`})]})})}function te({pending:e,children:t}){return(0,g.jsx)(`div`,{"aria-hidden":e||void 0,inert:e,children:t})}var ne={"pt-BR":{action:`Tentar novamente`,guidance:`Abra a pasta dashboard dentro de .agents e dê dois cliques novamente no arquivo executável.`,title:`Não foi possível carregar o dashboard`},"en-US":{action:`Try again`,guidance:`Open the dashboard folder inside .agents, then double-click the executable file again.`,title:`Unable to load the dashboard`}};function re({children:e,error:t,globalLoadingPending:n,locale:r,onRefresh:i,operations:a,snapshotNotice:o,setupRoute:s}){if(s!==null)return s;if(t&&a===null){let e=ne[r];return(0,g.jsx)(`main`,{className:`app-loading-boundary`,"aria-labelledby":`dashboard-load-error-title`,children:(0,g.jsxs)(`section`,{className:`app-loading-boundary__card`,role:`alert`,children:[(0,g.jsx)(`div`,{"aria-hidden":`true`,className:`app-loading-boundary__status-icon`,children:(0,g.jsx)(`svg`,{"aria-hidden":`true`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,g.jsx)(`path`,{d:`M12 8v4m0 4h.01M10.29 3.86 2.82 16.5A2 2 0 0 0 4.54 19.5h14.92a2 2 0 0 0 1.72-3L13.71 3.86a2 2 0 0 0-3.42 0Z`})})}),(0,g.jsxs)(`div`,{className:`app-loading-boundary__content`,children:[(0,g.jsx)(`p`,{className:`app-loading-boundary__eyebrow`,children:r===`pt-BR`?`Dashboard indisponível`:`Dashboard unavailable`}),(0,g.jsx)(`h1`,{id:`dashboard-load-error-title`,children:e.title}),(0,g.jsx)(`p`,{children:e.guidance})]}),(0,g.jsx)(`button`,{onClick:i,type:`button`,children:e.action})]})})}return a===null?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(_,{locale:r}),o,n?(0,g.jsx)(ee,{}):null,(0,g.jsx)(b,{area:`operations`,locale:r})]}):e}function A(e){let t=new Set(e.blocked.map(e=>e.id));return{reconciled:e.reconciled_ids.filter(e=>!t.has(e)).length,blocked:e.blocked.length,notReconciled:e.not_reconciled.length}}function j(e){let t=new Set(e.blocked.map(e=>e.id));return e.reconciled_ids.filter(e=>!t.has(e)).map(t=>{let n=e.outcomes?.find(e=>e.id===t);return{id:t,reason:n?.reason??null,status:n?.status??null}})}function M(e,t){return e===null?``:t===`pt-BR`?{completed:`Concluído`,delivered:`Entregue`,failed:`Falha técnica`,blocked:`Bloqueado`,cancelled:`Cancelado`}[e]??e:e}var ie={"Invocation is still running":`A invocação ainda está em execução. Foi preservada intencionalmente; isso não indica falha do comando.`,"Host terminated without delivery evidence":`O host encerrou sem evidências de entrega.`,"Host interrupted":`O host foi interrompido.`,"Child attempt stopped":`A tentativa do subagente foi encerrada.`,"Execution orphaned after the reconciliation grace period":`A execução ficou sem orquestrador ativo após o período de tolerância da reconciliação.`};function N(e,t){if(e===null)return t===`pt-BR`?`Motivo não informado.`:`No reason provided.`;if(t===`en-US`)return e;let n=e.match(/^Explicit orphan reconciliation found no active host invocation or terminal work outcome; repair is required before resuming \(Run (\S+)\)\.$/);if(n)return`A Run ${n[1]} ficou sem invocação ativa do host e sem evidência de um desfecho de entrega. A reconciliação registrou a interrupção; a entrega exige reparo e validação antes de retomar.`;let r=e.match(/^Execution (\S+) has no active orchestrator agent call after the reconciliation grace period\.?$/);return r?`A execução ${r[1]} não tem uma chamada de agente orquestrador ativa após o período de tolerância da reconciliação.`:ie[e.trim().replace(/\.$/,``)]??e}function P({result:e,locale:t,onDismiss:n}){let[r,i]=(0,m.useState)(!1),a=(0,m.useRef)(null),o=t===`pt-BR`,s=A(e),c=o?`Resultado da reconciliação manual`:`Manual reconciliation result`,l={reconciled:o?`Outros estados registrados`:`Other recorded outcomes`,blocked:o?`Desfechos bloqueados`:`Blocked outcomes`,notReconciled:o?`Não reconciliados`:`Not reconciled`},u=`${l.reconciled}: ${s.reconciled} · ${l.blocked}: ${s.blocked} · ${l.notReconciled}: ${s.notReconciled}`;return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsxs)(`section`,{className:`app-reconciliation-result`,"aria-label":c,children:[(0,g.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[(0,g.jsx)(`strong`,{children:c}),(0,g.jsx)(`p`,{children:u})]}),(0,g.jsxs)(`div`,{className:`app-reconciliation-actions`,children:[(0,g.jsx)(`button`,{ref:a,type:`button`,"aria-haspopup":`dialog`,onClick:()=>i(!0),children:o?`Veja mais`:`View details`}),(0,g.jsx)(`button`,{type:`button`,onClick:n,children:o?`Fechar`:`Dismiss`})]})]}),r?(0,g.jsx)(ae,{result:e,locale:t,title:c,summary:u,labels:l,onClose:()=>i(!1),restoreFocus:()=>a.current?.focus({preventScroll:!0})}):null]})}function ae({result:e,locale:t,title:n,summary:r,labels:i,onClose:a,restoreFocus:o}){let s=(0,m.useRef)(null),c=(0,m.useRef)(o),l=(0,m.useId)(),u=t===`pt-BR`;(0,m.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return e.showModal(),document.body.style.overflow=`hidden`,()=>{e.close(),document.body.style.overflow=t,c.current()}},[]);let d=[{label:i.reconciled,items:j(e),reasons:!0},{label:i.blocked,items:e.blocked,reasons:!0},{label:i.notReconciled,items:e.not_reconciled,reasons:!0}];return(0,g.jsxs)(`dialog`,{ref:s,className:`app-reconciliation-dialog`,"aria-labelledby":l,"aria-modal":`true`,onCancel:e=>{e.preventDefault(),a()},onKeyDown:e=>{if(e.key!==`Tab`)return;let t=Array.from(e.currentTarget.querySelectorAll(`button:not(:disabled), summary, [tabindex="0"]`)).filter(e=>e.getClientRects().length>0),n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r?.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n?.focus())},children:[(0,g.jsxs)(`header`,{children:[(0,g.jsx)(`h2`,{id:l,children:n}),(0,g.jsx)(`button`,{type:`button`,onClick:a,children:u?`Fechar detalhes`:`Close details`})]}),(0,g.jsxs)(`section`,{className:`app-reconciliation-details`,tabIndex:0,"aria-label":u?`Itens da reconciliação`:`Reconciliation items`,children:[(0,g.jsx)(`p`,{children:r}),(0,g.jsx)(`p`,{children:u?`A reconciliação registra o estado real de cada item. Desfechos bloqueados aparecem somente na categoria de bloqueios; um estado registrado não significa entrega concluída.`:`Reconciliation records each item's actual state. Blocked outcomes appear only in the blocked category; a recorded state does not imply completed delivery.`}),(0,g.jsx)(`p`,{children:u?`Última telemetria indica a coleta de tokens medidos. Registrar estados ou atualizar o snapshot sem novos tokens não altera esse horário.`:`Last telemetry means measured token collection. Recording states or refreshing the snapshot without new tokens does not change that time.`}),e.diagnostics?(0,g.jsxs)(`p`,{children:[u?`Reconciliação executada em`:`Reconciliation executed at`,` `,new Intl.DateTimeFormat(t,{dateStyle:`short`,timeStyle:`medium`}).format(new Date(e.diagnostics.completed_at)),` · Job: `,(0,g.jsx)(`code`,{children:e.diagnostics.job_id}),` · `,`Logs`,`: `,(0,g.jsx)(`code`,{children:e.diagnostics.log_directory})]}):null,(0,g.jsx)(`p`,{children:u?`Invocações ainda em execução são preservadas intencionalmente. Permanecer não reconciliado por esse motivo não indica falha do comando.`:`Invocations that are still running are intentionally preserved. Remaining unreconciled for this reason does not indicate a command failure.`}),d.map(e=>(0,g.jsxs)(`section`,{"aria-label":e.label,children:[(0,g.jsxs)(`h3`,{children:[e.label,` (`,e.items.length,`)`]}),e.items.length===0?(0,g.jsx)(`p`,{children:u?`Nenhum item nesta categoria.`:`No items in this category.`}):(0,g.jsx)(`ul`,{children:F(e.items).map(({item:n,key:r})=>(0,g.jsxs)(`li`,{children:[(0,g.jsx)(`code`,{children:n.id}),`status`in n&&typeof n.status==`string`?(0,g.jsx)(`p`,{children:M(n.status,t)}):null,e.reasons?(0,g.jsx)(`p`,{children:N(n.reason,t)}):null,e.reasons&&n.reason!==null&&N(n.reason,t)!==n.reason?(0,g.jsxs)(`details`,{children:[(0,g.jsx)(`summary`,{children:u?`Motivo original`:`Original reason`}),(0,g.jsx)(`p`,{children:n.reason})]}):null]},r))})]},e.label))]})]})}function F(e){let t=new Map;return e.map(e=>{let n=JSON.stringify([e.id,e.reason]),r=(t.get(n)??0)+1;return t.set(n,r),{item:e,key:`${n}:${r}`}})}var oe=`modulepreload`,se=function(e){return`/`+e},ce={},I=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=se(t,n),t=s(t),t in ce)return;ce[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:oe,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},le=(0,m.lazy)(async()=>({default:(await I(async()=>{let{DashboardHelpDialog:e}=await import(`./DashboardHelpDialog-BN8KQPrr.js`);return{DashboardHelpDialog:e}},__vite__mapDeps([0,1,2,3,4,5]))).DashboardHelpDialog}));function ue({costLocale:e,documentDetail:t,helpOpen:n,loadingArea:i,operations:a,reconciliationResult:c,refreshDialog:l,showTrace:u,trace:d,traceLink:h,traceLoadingTaskId:_,closeDocument:v,onCloseHelp:y,onCloseTrace:x,onDismissReconciliation:S,onOpenDocument:C,onOpenTrace:w,onOpenTraceChange:T,onOpenTraceMacro:E,onRefreshCancel:D,onRefreshFromDialog:O,setTraceLink:k}){return(0,g.jsxs)(g.Fragment,{children:[u?null:_?(0,g.jsx)(p,{locale:e,taskId:_}):d?(0,g.jsx)(f,{locale:e,onClose:x,onOpenChange:T,onOpenPrd:e=>E(`PRD`,e),onOpenSpec:e=>E(`SPEC`,e),trace:d}):null,h?.kind===`change`?(0,g.jsx)(r,{details:{kind:`change`,row:h.row},locale:e,onClose:()=>k(null)}):null,h?.kind===`macro`?(0,g.jsx)(s,{label:h.label,locale:e,onClose:()=>k(null),onOpenDocument:C,onOpenTrace:e=>{k(null),w(e)},row:h.row,runs:a.runs,specs:a.specs,tasks:a.tasks}):null,t?(0,g.jsx)(o,{detail:t.detail,error:t.error,label:t.label,locale:e,loading:!t.detail&&!t.error,onClose:v,onRetry:()=>C(t.kind,t.preview.id),preview:t.preview}):null,n?(0,g.jsx)(m.Suspense,{fallback:null,children:(0,g.jsx)(le,{locale:e,onClose:y})}):null,l===`choose`?(0,g.jsx)(`div`,{className:`app-refresh-dialog-backdrop`,children:(0,g.jsxs)(`section`,{"aria-label":`Atualizar dashboard`,"aria-modal":`true`,className:`app-refresh-dialog`,role:`dialog`,children:[(0,g.jsx)(`h2`,{children:e===`pt-BR`?`Atualizar dashboard`:`Refresh dashboard`}),(0,g.jsx)(`p`,{children:e===`pt-BR`?`Escolha uma atualização rápida ou reconcilie os itens que ainda estão em aberto.`:`Choose a quick refresh or reconcile work items that are still open.`}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`button`,{onClick:()=>O(!1),type:`button`,children:e===`pt-BR`?`Apenas atualizar dados`:`Refresh data only`}),(0,g.jsx)(`button`,{onClick:()=>O(!0),type:`button`,children:e===`pt-BR`?`Reconciliar itens abertos`:`Reconcile open work`})]}),(0,g.jsx)(`button`,{className:`app-refresh-cancel`,onClick:D,type:`button`,children:e===`pt-BR`?`Cancelar`:`Cancel`})]})}):null,l===`refreshing`||l===`reconciling`?(0,g.jsxs)(`section`,{"aria-live":`polite`,className:`app-refresh-status`,role:`status`,children:[(0,g.jsx)(`i`,{}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`strong`,{children:l===`reconciling`?e===`pt-BR`?`Reconciliando itens em aberto…`:`Reconciling open work…`:e===`pt-BR`?`Atualizando dados…`:`Refreshing data…`}),(0,g.jsx)(`span`,{children:e===`pt-BR`?`Você pode continuar usando o dashboard.`:`You can keep using the dashboard.`})]})]}):null,c!==null&&l===null?(0,g.jsx)(P,{result:c,locale:e,onDismiss:S}):null,i!==null&&l===null?(0,g.jsx)(b,{area:i,locale:e}):null]})}var de=(0,m.lazy)(async()=>({default:(await I(async()=>{let{PricingSettingsPage:e}=await import(`./PricingSettingsDialog-Prcs-ydy.js`);return{PricingSettingsPage:e}},__vite__mapDeps([6,1,2,3,4]))).PricingSettingsPage})),fe=(0,m.lazy)(async()=>({default:(await I(async()=>{let{ProjectSettingsPage:e}=await import(`./ProjectSettingsPage-HqGUImIG.js`);return{ProjectSettingsPage:e}},__vite__mapDeps([7,1,2,3,8]))).ProjectSettingsPage})),L=(0,m.lazy)(async()=>({default:(await I(async()=>{let{CostCalculationGuidePage:e}=await import(`./CostCalculationGuidePage-BW7Vy1cp.js`);return{CostCalculationGuidePage:e}},__vite__mapDeps([9,1,2,3]))).CostCalculationGuidePage})),pe=`/setup-pricing`,me=`/setup-project`,he=`/cost-calculation-guide`;function ge(e){let{api:t,costLocale:n,fxRate:r,navigate:i,pathname:a,pricing:o,refresh:s,setFxRate:c,setPricing:l}=e;return a===`/setup-pricing`?o===null?(0,g.jsxs)(`main`,{className:`app-state`,children:[(0,g.jsx)(`p`,{children:n===`pt-BR`?`Configuração do projeto`:`Project settings`}),(0,g.jsx)(`h1`,{children:n===`pt-BR`?`Carregando catálogo de preços…`:`Loading pricing catalog…`}),(0,g.jsx)(`button`,{onClick:()=>i(`/`),type:`button`,children:n===`pt-BR`?`Voltar ao dashboard`:`Back to dashboard`})]}):(0,g.jsx)(m.Suspense,{fallback:null,children:(0,g.jsx)(de,{catalog:o,fxRate:r,locale:n,onClose:()=>i(`/`),onSave:async e=>{l(await t.savePricing(e)),await s()},onSaveFxRate:async e=>{c(await t.saveFxRate(e)),await s()}})}):a===`/cost-calculation-guide`&&o!==null?(0,g.jsx)(m.Suspense,{fallback:null,children:(0,g.jsx)(L,{catalog:o,fxRate:r,locale:n,onClose:()=>i(`/`)})}):a===`/setup-project`?(0,g.jsx)(m.Suspense,{fallback:null,children:(0,g.jsx)(fe,{api:t,locale:n,onClose:()=>i(`/`)})}):null}var _e=(0,m.lazy)(async()=>({default:(await I(async()=>{let{TraceabilityWorkspace:e}=await import(`./TraceabilityWorkspace-CNpmQMO4.js`);return{TraceabilityWorkspace:e}},__vite__mapDeps([10,1,2,3,11,12,13,14]))).TraceabilityWorkspace}));function ve({costs:e,costLocale:t,currency:n,dashboardView:r,failedArea:i,lastUpdatedAt:a,loadCostDetail:o,loadCostReadModelPage:s,loadCostRunPage:c,loadCostGroupPage:u,loadingArea:d,onActiveDataChange:f,onCurrencyChange:p,onLoadingChange:h,onLocaleChange:_,onOpenTrace:v,onLoadMoreTraceTasks:b,onRefresh:S,onRetry:C,onSelectTraceTask:w,onOpenTraceChange:T,onOpenTraceMacro:E,operations:D,selectedTraceTaskId:O,trace:k,traceLoadingTaskId:ee,traceTasksHasMore:te,traceTasksLoading:ne,traceTasks:re}){return r===`cost-monitor`?e===null?()=>i===`costs`?(0,g.jsx)(x,{locale:t,onRetry:C}):(0,g.jsx)(y,{area:`costs`,locale:t}):r=>(0,g.jsx)(m.Suspense,{fallback:(0,g.jsx)(y,{area:`costs`,locale:t}),children:(0,g.jsx)(l,{currency:n,data:e,embedded:!0,globalFilters:r,lastUpdatedAt:a,locale:t,loading:d===`costs`,loadDetail:o,loadReadModelPage:s,loadRunPage:c,loadGroupPage:u,onActiveDataChange:f,onCurrencyChange:p,onLoadingChange:h,onLocaleChange:_,onOpenTrace:v,onRefresh:S,operations:D})}):r===`traceability`?()=>(0,g.jsx)(m.Suspense,{fallback:(0,g.jsx)(y,{area:`operations`,locale:t}),children:(0,g.jsx)(_e,{loadingTaskId:ee,locale:t,onOpenChange:T,onOpenPrd:e=>E(`PRD`,e),onOpenSpec:e=>E(`SPEC`,e),onLoadMoreTasks:b,onSelectTask:w,selectedTaskId:O,tasks:re.length>0?re:D.tasks,hasMoreTasks:te,isLoadingTasks:ne,trace:k})}):r===null?(0,g.jsx)(`span`,{"aria-hidden":`true`,hidden:!0}):void 0}function ye({currency:e,locale:t,onCurrencyChange:n,onHelpOpen:r,onNavigate:i,pricingSetupPath:a,projectSetupPath:o,costCalculationGuidePath:s}){return(0,g.jsxs)(`div`,{className:`dashboard-global-settings`,children:[(0,g.jsxs)(`label`,{children:[(0,g.jsx)(`span`,{children:t===`pt-BR`?`Moeda`:`Currency`}),(0,g.jsxs)(`select`,{"aria-label":t===`pt-BR`?`Moeda`:`Currency`,onChange:e=>n(e.target.value),value:e,children:[(0,g.jsx)(`option`,{value:`BRL`,children:`BRL · Real brasileiro`}),(0,g.jsx)(`option`,{value:`USD`,children:`USD · US Dollar`})]})]}),(0,g.jsx)(`button`,{className:`dashboard-help-open`,onClick:r,type:`button`,children:t===`pt-BR`?`Central de Ajuda`:`Open help and guides`}),(0,g.jsx)(`button`,{className:`dashboard-help-open`,onClick:()=>i(a),type:`button`,children:t===`pt-BR`?`Configurar preços e câmbio`:`Configure pricing and FX`}),(0,g.jsx)(`button`,{className:`dashboard-help-open`,onClick:()=>i(o),type:`button`,children:t===`pt-BR`?`Configurar projeto`:`Configure project`}),(0,g.jsx)(`button`,{className:`dashboard-help-open`,onClick:()=>i(s),type:`button`,children:t===`pt-BR`?`Guia de cálculo de custos`:`Cost calculation guide`})]})}var be={preset:`all`,range:a(`this-month`)};function R(e){return e.preset===`all`?{from:null,to:null}:{from:e.range.start,to:e.range.end}}function xe(e,t){let n=R(e),r=R(t);return n.from===r.from&&n.to===r.to}function Se({model:e}){let{operations:t,error:n,globalLoadingPending:r,costLocale:i,refresh:a,snapshotNotice:o,setupRoute:s,failedArea:l,retryLastLoad:u,costs:d,currency:f,dashboardView:p,lastUpdatedAt:m,loadCostDetail:h,loadCostReadModelPage:_,loadCostRunPage:v,loadCostGroupPage:y,loadingArea:b,setDisplayedCosts:x,setCurrency:S,setCostSurfaceLoading:C,changeDashboardLocale:w,loadMoreTraceTasks:T,openTrace:E,setRefreshDialog:D,setSelectedTraceTaskId:O,openTraceChange:k,openTraceMacro:ne,renderedOperations:A,selectedTraceTaskId:j,trace:M,traceLoadingTaskId:ie,traceTasksHasMore:N,traceTasksLoading:P,traceTasks:ae,capabilityNavigation:F,boardTotals:oe,boardKindTotals:se,boardExportSource:ce,detailExportSource:I,boardStates:le,operationsPeriod:de,entityPage:fe,dashboardIdentity:L,operationsLoading:ge,factualCostFact:_e,factualCostPeriods:be,setOperationsSurfaceLoading:R,operationsSurfaceLoading:Se,currentCostByRun:Ce,loadOperationsEntityPage:we,loadOperationsLifecyclePage:Te,loadOperationsDetails:Ee,entityPageKind:z,loadFilteredOperationsPage:De,loadFilteredBoard:Oe,loadWorkListFilters:ke,loadWorkListPage:Ae,workListFiltersRef:je,boardFiltersRef:Me,workListPage:Ne,overviewStatusPages:Pe,loadOverviewStatusPage:B,overviewClassificationPages:V,loadOverviewClassificationPage:H,openDocument:Fe,api:Ie,setError:U,operationsPeriodRef:Le,setOperationsPeriod:W,operationsDetailLoadedRef:Re,operationsDetailCancelRef:ze,operationsDetailAbortRef:Be,operationsPageAbortRef:Ve,resetWorkListPage:He,operationsPageRequestVersionRef:Ue,refreshVersion:We,costSummaryAbortRef:Ge,costSummaryRequestVersion:Ke,setEntityPage:qe,costsLoadedRef:Je,setCosts:Ye,setPeriodTransitionPending:Xe,periodTransitionVersionRef:Ze,setLoadingArea:G,navigate:K,setHelpOpen:Qe,closeDocument:$e,documentDetail:et,helpOpen:tt,reconciliationResult:nt,setReconciliationResult:rt,refreshDialog:it,setTrace:at,traceLink:ot,setTraceLink:st,refreshFromDialog:ct}=e,{loadMoreBoard:lt,overviewStatusPageKey:ut,overviewClassificationPageKey:dt,boardRequestVersionRef:ft,boardAbortControllersRef:pt,boardInFlightRef:mt,boardInitialPageRef:ht,boardLoadedRef:gt,setBoardTotals:_t,setBoardKindTotals:vt,setBoardStates:yt,setOverviewStatusPages:q,setOverviewClassificationPages:bt,setOperationsLoading:J}=e;return(0,g.jsxs)(re,{error:n,globalLoadingPending:r,locale:i,onRefresh:()=>void a(),operations:t,snapshotNotice:o,setupRoute:s,children:[(0,g.jsxs)(te,{pending:r,children:[n?(0,g.jsxs)(`div`,{"aria-live":`assertive`,className:`app-warning app-error`,role:`alert`,children:[(0,g.jsx)(`span`,{children:n}),l?(0,g.jsx)(`button`,{onClick:u,type:`button`,children:i===`pt-BR`?`Tentar novamente`:`Try again`}):null,(0,g.jsx)(`button`,{"aria-label":i===`pt-BR`?`Fechar erro`:`Dismiss error`,onClick:()=>U(null),type:`button`,children:`×`})]}):null,(0,g.jsx)(c,{alternateContent:ve({costs:d,costLocale:i,currency:f,dashboardView:p,failedArea:l,lastUpdatedAt:m,loadCostDetail:h,loadCostReadModelPage:_,loadCostRunPage:v,loadCostGroupPage:y,loadingArea:b,onActiveDataChange:x,onCurrencyChange:S,onLoadingChange:C,onLocaleChange:w,onLoadMoreTraceTasks:T,onOpenTrace:e=>void E(e),onRefresh:()=>D(`choose`),onRetry:u,onSelectTraceTask:e=>{O(e),E(e)},onOpenTraceChange:k,onOpenTraceMacro:ne,operations:A,selectedTraceTaskId:j,trace:M,traceLoadingTaskId:ie,traceTasksHasMore:N,traceTasksLoading:P,traceTasks:ae}),capabilityNavigation:F,boardTotals:oe,boardKindTotals:se,boardExportSource:ce,detailExportSource:I,boardStates:le,data:A,lastUpdatedAt:m,datePreset:de.preset,dateRange:de.range,entityPage:fe,dashboardTitle:L.title,repositoryName:L.repositoryName,loading:ge,locale:i,currency:f,factualCostFact:_e,costLoading:d===null&&l!==`costs`,factualCostPeriods:be,onLoadingChange:R,resolveRunCost:d===null?void 0:e=>Ce.get(e)??null,onLocaleChange:w,onDetailDataRequest:e=>{let t=e===`conversations`?`conversations`:e===`executions`?`executions`:e===`runs`?`runs`:null;t===null?e===`changes`||e===`decisions`?Te(e):Ee():we(t)},onLoadMacroMetrics:()=>{t?.summary.overview_metrics?.macro_metrics===void 0&&Ee()},onEntityPageChange:e=>{z===`changes`||z===`decisions`?Te(z,e):we(z,e)},onEntityFiltersChange:De,onBoardFiltersChange:Oe,onWorkListFiltersChange:ke,onWorkListPageChange:e=>void Ae(je.current,e),onBoardTypeChange:e=>Oe({...Me.current,kind:e===`all`?``:e}),onWorkListTypeChange:e=>void Ae({...je.current,kind:e===`all`?``:e}),onLoadMoreBoard:e=>void lt(e),workListPage:Ne,statusPage:(e,t)=>Pe[ut(e,t)],onLoadStatusPage:(e,t,n)=>void B(e,t,n),classificationPage:(e,t)=>V[dt(e,t)],onLoadClassificationPage:(e,t,n)=>void H(e,t,n),onOpenDocument:(e,t)=>void Fe(e,t),onOpenTask:E,onPriorityChange:async e=>{try{await Ie.saveWorkPriority(e)}catch(e){throw U(e instanceof Error?e.message:String(e)),e}},onDateChange:(e,t)=>{let n={preset:e,range:t};if(xe(Le.current,n)){W(n);return}Re.current=!1,ze.current?.(),ze.current=null,Be.current?.abort(),Be.current=null,Ve.current?.abort(),Ve.current=null,He(),++Ue.current,ft.current+=1;for(let e of pt.current.values())e.abort();pt.current.clear(),mt.current.clear(),ht.current.clear(),gt.current={},_t({}),vt({}),yt({}),q({}),bt({}),++We.current,Ge.current?.abort(),Ge.current=null,++Ke.current,qe({offset:0,total:null,loading:!1,error:null}),Je.current=!1,Ye(null),x(null),J(!0),Ze.current+=1,Xe(!0),G(`operations`),W(n)},onRefresh:()=>D(`choose`),settings:(0,g.jsx)(ye,{costCalculationGuidePath:he,currency:f,locale:i,onCurrencyChange:S,onHelpOpen:()=>Qe(!0),onNavigate:K,pricingSetupPath:pe,projectSetupPath:me})}),(0,g.jsx)(ue,{closeDocument:$e,costLocale:i,documentDetail:et,helpOpen:tt,loadingArea:b??(d===null&&l!==`costs`?`costs`:Se||Object.values(le).some(e=>e.loading)?`operations`:null),operations:A,reconciliationResult:nt,refreshDialog:it,showTrace:p===`traceability`,trace:M,traceLink:ot,traceLoadingTaskId:ie,onCloseHelp:()=>Qe(!1),onCloseTrace:()=>at(null),onDismissReconciliation:()=>rt(null),onOpenDocument:(e,t)=>void Fe(e,t),onOpenTrace:e=>void E(e),onOpenTraceChange:k,onOpenTraceMacro:ne,onRefreshCancel:()=>D(null),onRefreshFromDialog:e=>void ct(e),setTraceLink:e=>st(e)})]}),r?(0,g.jsx)(ee,{}):null]})}var Ce=(e,t)=>`${e}:${t}`,we=(e,t)=>`${e}:${t}`,Te=[`definition`,`planning`,`ready`,`executing`,`verifying`,`completed`,`blocked`,`cancelled`,`failed`],Ee=`/zaip-cost-monitor`,z=`zaip-dashboard-session-token`,De=`zaip-dashboard-locale`,Oe=`zaip-dashboard-currency`;function ke(){return window.localStorage.getItem(`zaip-dashboard-locale`)===`en-US`?`en-US`:`pt-BR`}function Ae(e){return e.replace(/\/+$/,``)===Ee?`cost-monitor`:null}function je(){let e=new URL(window.location.href),t=e.searchParams.get(`token`)??window.localStorage.getItem(`zaip-dashboard-session-token`)??window.sessionStorage.getItem(`zaip-dashboard-session-token`)??``;return t&&(window.localStorage.setItem(z,t),window.sessionStorage.setItem(z,t)),e.searchParams.has(`token`)&&(e.searchParams.delete(`token`),window.history.replaceState(null,``,`${e.pathname}${e.search}${e.hash}`)),t}var Me=class{token;constructor(e){this.token=e}ready(){return this.get(`/api/v2/ready`)}captureTelemetry(){return this.post(`/api/v2/capture-telemetry`)}dashboardIdentity(){return this.get(`/api/v2/dashboard-identity`)}operations(e,t=`detail`,n,r=!1){let a=`${i.operations}?scope=${t}${r?`&fresh=1`:``}`;return this.get(H(a,e),n)}sqliteViewPage(e,t,n={},r){let i=new URLSearchParams({view:e,offset:String(n.offset??0)});return n.limit!==void 0&&i.set(`limit`,String(n.limit)),n.query&&i.set(`query`,n.query),n.status&&i.set(`status`,n.status),n.risk&&i.set(`risk`,n.risk),n.provider&&i.set(`provider`,n.provider),n.model&&i.set(`model`,n.model),n.agent&&i.set(`agent`,n.agent),n.phase&&i.set(`phase`,n.phase),n.origin&&i.set(`origin`,n.origin),n.workType&&i.set(`workType`,n.workType),n.priority&&i.set(`priority`,n.priority),n.kind&&i.set(`kind`,n.kind),this.get(H(`/api/v2/sqlite-views?${i.toString()}`,t),r)}operationsBoard(e,t,n=0,r,a,o=4){let s=new URLSearchParams({scope:`board`,stage:t,offset:String(n),limit:String(o)});return r?.query&&s.set(`query`,r.query),r?.status&&s.set(`status`,r.status),r?.risk&&s.set(`risk`,r.risk),r?.origin&&s.set(`origin`,r.origin),r?.kind&&s.set(`kind`,r.kind),this.get(H(`${i.operations}?${s.toString()}`,e),a)}traceabilityTasks(e=0,t=10){let n=new URLSearchParams({scope:`traceability`,offset:String(e),limit:String(t)});return this.get(`${i.operations}?${n}`)}operationsClassification(e,t,n,r=0,a,o=50){let s=new URLSearchParams({scope:`classification`,kind:t,classification:n,offset:String(r),limit:String(o)});return this.get(H(`${i.operations}?${s.toString()}`,e),a)}operationsEntityPage(e,t,n=0,r,a){let o=Ne(t,n,r);return this.get(H(`${i.operations}/runs?${o}`,e),a)}operationsLifecyclePage(e,t,n=0,r,a){let o=Ne(t,n,r);return this.get(H(`${i.operations}/entities?${o}`,e),a)}operationsReadModelPage(e,t,n=0,r=50,a=``,o){let s=new URLSearchParams({kind:t,offset:String(n),limit:String(r)});return a&&s.set(`query`,a),this.get(H(`${i.operations}/read-models?${s.toString()}`,e),o)}costMonitor(e=`BRL`,t,n=`detail`,r,a,o=!1){let s=new URLSearchParams({currency:e,scope:n});o&&s.set(`fresh`,`1`);for(let[e,t]of Object.entries(a??{}))t&&s.set(e,t);return this.get(H(`${i.costMonitor}?${s.toString()}`,t),r)}costMonitorRuns(e=`BRL`,t,n,r=100,a,o){let s=new URLSearchParams({currency:e,scope:`runs`,offset:String(n),limit:String(r)});for(let[e,t]of Object.entries(o??{}))t&&s.set(e,t);return this.get(H(`${i.costMonitor}?${s.toString()}`,t),a)}snapshot(e=`BRL`,t){return this.get(H(`${i.snapshot}?currency=${e}`,t))}reconcileOpenWork(e=`BRL`,t){return this.post(H(`${i.reconcileOpenWork}?currency=${e}`,t),B)}refreshProjection(e=`BRL`,t){return this.post(H(`${i.refreshProjection}?currency=${e}`,t),B)}task(e){return this.get(i.task(e))}prd(e){return this.get(i.prd(e))}spec(e){return this.get(i.spec(e))}taskTrace(e,t){return this.get(i.taskTrace(e),t)}pricing(){return this.get(`/api/v2/pricing`)}async savePricing(e){let t=await fetch(`/api/v2/pricing`,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify(e)});if(!t.ok)throw Error(`Pricing update failed with HTTP ${t.status}`);return await t.json()}fxRate(){return this.get(`/api/v2/fx-rate`)}agentCatalog(){return this.get(i.agentCatalog)}agentPortraitUrl(e){return`/api/v2/agent-catalog-assets/${encodeURIComponent(e)}?token=${encodeURIComponent(this.token)}`}projectSettings(){return this.get(i.projectSettings)}projectOverview(){return this.get(`${i.projectSettings}/overview`)}async saveWorkPriority(e){let t=await fetch(i.workPriority,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify({item_ids:e})});if(!t.ok)throw Error(`Work priority update failed with HTTP ${t.status}`);return await t.json()}async saveProjectSettings(e){let t=await fetch(i.projectSettings,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.error??`Project settings update failed with HTTP ${t.status}`)}return await t.json()}async saveAgentCatalog(e){let t=e.map(({nickname_candidates:e,...t})=>t),n=await fetch(i.agentCatalog,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify({agents:t})});if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??`Agent catalog update failed with HTTP ${n.status}`)}return await n.json()}async saveFxRate(e){let t=await fetch(`/api/v2/fx-rate`,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify({rate:e})});if(!t.ok)throw Error(`FX update failed with HTTP ${t.status}`);return await t.json()}async get(e,t){let n=await V(e,{cache:`no-cache`,headers:{"x-zaip-session":this.token}},Pe,t);if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??`Dashboard API failed with HTTP ${n.status}`)}return await n.json()}async post(e,t=Pe){let n=await V(e,{method:`POST`,headers:{"x-zaip-session":this.token}},t);if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??`Dashboard API failed with HTTP ${n.status}`)}return await n.json()}};function Ne(e,t,n){let r=new URLSearchParams({kind:e,offset:String(t),limit:`100`});return n?.query&&r.set(`query`,n.query),n?.status&&r.set(`status`,n.status),n?.risk&&r.set(`risk`,n.risk),r.toString()}var Pe=6e4,B=18e4;async function V(e,t,n=Pe,r){let i=new AbortController,a=()=>i.abort();r?.addEventListener(`abort`,a,{once:!0}),r?.aborted&&i.abort();let o=window.setTimeout(()=>i.abort(),n);try{return await fetch(e,{...t,signal:i.signal})}catch(e){throw e instanceof DOMException&&e.name===`AbortError`?Error(`A leitura demorou mais de ${Math.ceil(n/1e3)} segundos. Tente novamente.`):e}finally{window.clearTimeout(o),r?.removeEventListener(`abort`,a)}}function H(e,t){if(t===void 0)return e;let n=new URL(e,`http://dashboard.local`);return t.from!==null&&n.searchParams.set(`from`,t.from),t.to!==null&&n.searchParams.set(`to`,t.to),`${n.pathname}${n.search}`}function Fe(e){return e.projection_refresh_completed}function Ie(e,t){return{reconciliation:e.reconciliation,dismissProgressDialog:!0,applySnapshotState:t,reloadQuickProjection:t&&Fe(e)}}var U={"pt-BR":{label:`Áreas do dashboard`,operations:`Operação`,operationsHint:`Trabalho em andamento e priorização`,costs:`Monitor de Custos`,costsHint:`Tempo, tokens e custo`,traceability:`Rastreabilidade`,traceabilityHint:`Ciclo completo em 6 etapas`},"en-US":{label:`Dashboard areas`,operations:`Operations`,operationsHint:`Lifecycle and work in progress`,costs:`Cost Monitor`,costsHint:`Time, tokens, and cost`,traceability:`Traceability`,traceabilityHint:`Complete 6-stage lifecycle`}};function Le({activeView:e,locale:t,onChange:n}){let r=U[t],i=e=>{n(e),window.requestAnimationFrame(()=>{document.querySelector(`.dashboard-global-controls`)?.scrollIntoView({behavior:`smooth`,block:`start`})})};return(0,g.jsxs)(`nav`,{"aria-label":r.label,className:`dashboard-capability-nav`,children:[(0,g.jsxs)(`button`,{"aria-current":e===`cost-monitor`?`page`:void 0,className:e===`cost-monitor`?`is-active`:void 0,onClick:()=>i(`cost-monitor`),type:`button`,children:[(0,g.jsx)(Re,{}),(0,g.jsxs)(`span`,{children:[(0,g.jsx)(`strong`,{children:r.costs}),(0,g.jsx)(`small`,{children:r.costsHint})]})]}),(0,g.jsxs)(`button`,{"aria-current":e===`operations`?`page`:void 0,className:e===`operations`?`is-active`:void 0,onClick:()=>i(`operations`),type:`button`,children:[(0,g.jsx)(W,{}),(0,g.jsxs)(`span`,{children:[(0,g.jsx)(`strong`,{children:r.operations}),(0,g.jsx)(`small`,{children:r.operationsHint})]})]}),(0,g.jsxs)(`button`,{"aria-current":e===`traceability`?`page`:void 0,className:e===`traceability`?`is-active`:void 0,onClick:()=>i(`traceability`),type:`button`,children:[(0,g.jsx)(ze,{}),(0,g.jsxs)(`span`,{children:[(0,g.jsx)(`strong`,{children:r.traceability}),(0,g.jsx)(`small`,{children:r.traceabilityHint})]})]})]})}function W(){return(0,g.jsxs)(`svg`,{"aria-hidden":`true`,className:`lucide lucide-square-kanban`,viewBox:`0 0 24 24`,children:[(0,g.jsx)(`rect`,{height:`18`,rx:`2`,width:`18`,x:`3`,y:`3`}),(0,g.jsx)(`path`,{d:`M8 7v7`}),(0,g.jsx)(`path`,{d:`M12 7v4`}),(0,g.jsx)(`path`,{d:`M16 7v9`})]})}function Re(){return(0,g.jsxs)(`svg`,{"aria-hidden":`true`,className:`lucide lucide-circle-dollar-sign`,viewBox:`0 0 24 24`,children:[(0,g.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,g.jsx)(`path`,{d:`M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8`}),(0,g.jsx)(`path`,{d:`M12 18V6`})]})}function ze(){return(0,g.jsxs)(`svg`,{"aria-hidden":`true`,className:`lucide lucide-route`,viewBox:`0 0 24 24`,children:[(0,g.jsx)(`circle`,{cx:`6`,cy:`19`,r:`3`}),(0,g.jsx)(`path`,{d:`M9 19h6.5a3.5 3.5 0 0 0 0-7h-7a3.5 3.5 0 0 1 0-7H18`}),(0,g.jsx)(`circle`,{cx:`18`,cy:`5`,r:`3`})]})}function Be(e){m.useEffect(()=>{if(!e)return;let t=new EventSource(`/api/v2/browser-lease?token=${encodeURIComponent(e)}`);return()=>t.close()},[e])}function Ve(e,t,n){return(0,g.jsx)(`div`,{className:`dashboard-capability-shell dashboard-capability-shell--${e??`initial`}`,children:(0,g.jsx)(Le,{activeView:e,locale:t,onChange:n})})}function He(e){return t=>{window.history.pushState(null,``,t),e(t),window.scrollTo({left:0,top:0})}}function Ue(e,t,n){return new Map((t??e)?.runs.map(e=>[e.run_id,n===`USD`?e.estimated_usd:e.estimated_brl])??[])}function We(e,t,n){let r=t??e;if(r?.currency!==n)return{fact:{state:`unavailable`,knownSum:null,coverage:null},periods:void 0};let i=r.overview.coverage[n===`USD`?`usd`:`brl`],a=n===`USD`?r.overview.estimated_usd:r.overview.estimated_brl,o={known:i,total:r.overview.run_count};return{fact:a===null?{state:`unavailable`,knownSum:null,coverage:o}:i<r.overview.run_count?{state:`partial`,knownSum:a,coverage:o}:{state:`complete`,knownSum:a,coverage:o},periods:{day:r.groups.daily,month:r.groups.monthly,year:r.groups.annual}}}var Ge={title:`Dashboard ZAIP AIOS`,repositoryName:``};function Ke(e,t){let n=typeof t.title==`string`?t.title.trim():``,r=typeof t.repository_name==`string`?t.repository_name.trim():``;return{title:n||e.title,repositoryName:r}}function qe(e,t,n,r,i,a,o,s){s(null),e===`costs`?r():e===`traceability`&&t?i(t):e===`operations`&&n!==null?a():o()}function Je(e,t,n,r,i,a,o,s,c){return ge({api:e,costLocale:t,fxRate:n,navigate:r,pathname:i,pricing:a,refresh:async()=>{await o()},setFxRate:s,setPricing:c})}function Ye(e){return async t=>{if(e.setDashboardView(t),window.scrollTo({left:0,top:0}),t===`cost-monitor`?S({costsLoaded:e.costsLoadedRef.current,currency:e.currency,snapshotCurrency:e.costs?.currency})&&(e.costSummaryAbortRef.current===null||e.costSummaryAbortRef.current.signal.aborted)&&e.loadCostSummary():e.costSummaryAbortRef.current?.abort(),t===`traceability`){let t=e.traceTasks;if(t.length===0){let n=e.boardRequestVersionRef.current;if(t=await e.loadMoreTraceTasks(!1,!0),n!==e.boardRequestVersionRef.current)return;e.setTraceTasks(t)}let n=t.toSorted((e,t)=>Date.parse(t.finished_at??t.updated_at)-Date.parse(e.finished_at??e.updated_at)),r=n.find(e=>e.status===`completed`)??n[0];r&&(e.setSelectedTraceTaskId(r.id),e.openTrace(r.id));return}e.setTrace(null),e.setTraceLoadingTaskId(null)}}function Xe(e,t=new Date){return e.preset===`custom`?e:e.preset===`all`?{...e,range:a(`this-month`,t)}:{...e,range:a(e.preset,t)}}function Ze(e=new Date){let t=n(e.toISOString(),`day`);if(t===null)throw RangeError(`Invalid Sao Paulo day anchor`);let r=e.getTime(),i=r+1800*60*1e3;for(;n(new Date(i).toISOString(),`day`)===t;)i+=360*60*1e3;for(;i-r>1;){let e=Math.floor((r+i)/2);n(new Date(e).toISOString(),`day`)===t?r=e:i=e}return Math.max(1,i-e.getTime()+25)}function G(e){return typeof e==`number`?e:null}function K(e){return typeof e==`number`?{known_sum:e,unknown:0,complete:!0,coverage_ratio:1}:{known_sum:0,unknown:1,complete:!1,coverage_ratio:0}}function Qe(e){return Object.hasOwn(e,`total_duration`)?G(e.total_duration):G(e.cost_monitor_total_duration)}function $e(e,t,n){let{filters:r,query:i}=e;return{offset:t,limit:n,...i===void 0||i===``?{}:{query:i},...r.provider?{provider:r.provider}:{},...r.model?{model:r.model}:{},...r.agent?{agent:r.agent}:{},...r.phase?{phase:r.phase}:{},...r.status?{status:r.status}:{},...r.origin?{origin:r.origin}:{},...r.workType?{workType:r.workType}:{},...r.priority?{priority:r.priority}:{},...r.risk?{risk:r.risk}:{}}}function et(e){let t=Qe(e),n=Number(e.duration_unknown??+(t===null)),r=t??G(e.duration_known)??0;return{key:String(e.key??e.period_key??`total`),label:String(e.label??e.key??e.period_key??``),latest_started_at:typeof e.latest_started_at==`string`?e.latest_started_at:``,persona:typeof e.persona==`string`?e.persona:null,job:typeof e.job==`string`?e.job:null,run_count:Number(e.total_run_count??e.invocation_count??0),task_count:G(e.task_count),conversation_count:Number(e.conversation_count??0),prd_count:G(e.prd_count),spec_count:G(e.spec_count),evidence_count:G(e.evidence_count),test_count:G(e.validation_count),event_count:Number(e.source_event_count??0),total_tokens:G(e.total_tokens),estimated_usd:G(e.total_cost_usd),estimated_brl:G(e.total_cost_brl),duration_ms:t,duration:{known_sum:r,unknown:n,complete:n===0,coverage_ratio:+(n===0)},coverage:{events:0,tokens:0,usd:0,brl:0}}}async function tt(e,t){let{from:n,limit:r,offset:i,signal:a,to:o,view:s}=t,c=n===void 0||o===void 0?void 0:{from:n,to:o};if(s===`daily`){let n=await e.sqliteViewPage(`cost_monitor_daily`,c,$e(t,i,r),a);return{offset:n.offset,limit:n.limit,total_count:n.total_count,has_more:n.has_more,rows:n.rows.map(et),...n.period_averages===void 0?{}:{period_averages:n.period_averages},...n.totals===void 0?{}:{totals:et(n.totals)}}}let l={monthly:`cost_monitor_monthly`,annual:`cost_monitor_annual`,agents:`cost_monitor_zaip_agents`,models:`cost_monitor_models`,providers:`cost_monitor_providers`}[s],u=await e.sqliteViewPage(l,c,$e(t,i,r),a);return{offset:u.offset,limit:u.limit,total_count:u.total_count,has_more:u.has_more,rows:u.rows.map(et),...u.period_averages===void 0?{}:{period_averages:u.period_averages},...u.totals===void 0?{}:{totals:et(u.totals)}}}async function nt(e,t){let{filters:n,from:r,limit:i=10,offset:a,signal:o,to:s}=t,c=await e.sqliteViewPage(`cost_monitor_agent_invocations`,r===void 0||s===void 0?void 0:{from:r,to:s},{offset:a,limit:i,...n?.query?{query:n.query}:{},...n?.provider?{provider:n.provider}:{},...n?.model?{model:n.model}:{},...n?.agent?{agent:n.agent}:{},...n?.phase?{phase:n.phase}:{},...n?.status?{status:n.status}:{},...n?.priority?{priority:n.priority}:{},...n?.risk?{risk:n.risk}:{},...n?.origin?{origin:n.origin}:{},...n?.workType?{workType:n.workType}:{}},o);return{page_only:!0,runs:c.rows.map(rt),run_page:{offset:c.offset,limit:c.limit,total:c.total_count,has_more:c.has_more}}}function rt(e){let t=(e,t)=>typeof e==`string`?e:t,n=e=>typeof e==`number`?e:null,r=t(e.agent_invocation_id,`unavailable`),i=typeof e.task_id==`string`?e.task_id:null,a=typeof e.spec_id==`string`?e.spec_id:null,o=typeof e.prd_id==`string`?e.prd_id:null,s=t(e.phase,`execution`),c=e.duration_provenance===`observed`||e.duration_provenance===`reconciled`||e.duration_provenance===`estimated`||e.duration_provenance===`legacy_inferred`?e.duration_provenance:`unavailable`,l=Object.hasOwn(e,`calculated_cost_usd`)?n(e.calculated_cost_usd):n(e.cost_usd),u=n(e.current_fx_rate)??n(e.fx_rate),d=n(e.recorded_cost_usd)??n(e.recorded_usd),f=Object.hasOwn(e,`recorded_fx_rate`)?n(e.recorded_fx_rate):n(e.fx_rate),p=n(e.recorded_brl)??(!Object.hasOwn(e,`recorded_brl`)&&d!==null?n(e.cost_brl):null),m=l!==null&&u!==null?Math.round(l*u*1e6)/1e6:null;return{run_id:r,execution_id:typeof e.execution_id==`string`?e.execution_id:null,conversation_id:t(e.run_id,r),task_id:i,task_title:t(e.task_title,i??`Tarefa avulsa`),task_status:t(e.task_status,`unavailable`),priority:t(e.priority,`unavailable`),risk:t(e.risk,`unavailable`),spec_id:a,prd_id:o,change_id:typeof e.change_id==`string`?e.change_id:null,parent_run_id:typeof e.parent_agent_invocation_id==`string`?e.parent_agent_invocation_id:null,run_role:e.invocation_kind===`subagent`?`subagent`:`orchestrator`,run_kind:e.run_kind===`subrun`?`subrun`:`run`,run_purpose:`execution`,requires_finalizer:!1,client:t(e.client,`unavailable`),agent:t(e.zaip_agent,`unavailable`),agent_name:t(e.zaip_agent,`unavailable`),provider:typeof e.provider==`string`?e.provider:null,model:t(e.model,`unavailable`),requested_model:t(e.requested_model,`unavailable`),reasoning_effort:typeof e.reasoning_effort==`string`?e.reasoning_effort:null,effective_reasoning_effort:typeof e.effective_reasoning_effort==`string`?e.effective_reasoning_effort:null,service_tier:typeof e.service_tier==`string`?e.service_tier:null,call_count:n(e.llm_call_count),status:t(e.status,`completed`),phase:s,origin:o===null?a===null?i===null?`conversation`:`task`:`spec`:`prd`,work_type:e.work_type===`rework`?`rework`:`new`,started_at:t(e.occurred_at,``),finished_at:typeof e.finished_at==`string`?e.finished_at:null,duration_ms:n(e.duration_ms),duration_provenance:c,estimation_basis:typeof e.estimation_basis==`string`?e.estimation_basis:null,source_started_at:typeof e.source_started_at==`string`?e.source_started_at:null,source_finished_at:typeof e.source_finished_at==`string`?e.source_finished_at:null,capture_lag_ms:n(e.capture_lag_ms),event_count:n(e.source_event_count),input_tokens:n(e.input_tokens),cached_input_tokens:n(e.cached_input_tokens),output_tokens:n(e.output_tokens),reasoning_tokens:n(e.reasoning_tokens),total_tokens:n(e.total_tokens),uncached_input_tokens:n(e.uncached_input_tokens),visible_output_tokens:n(e.visible_output_tokens),input_rate_usd_per_million:n(e.input_rate_usd_per_million),cached_input_rate_usd_per_million:n(e.cached_input_rate_usd_per_million),output_rate_usd_per_million:n(e.output_rate_usd_per_million),reasoning_rate_usd_per_million:n(e.reasoning_rate_usd_per_million),context_input_multiplier:n(e.context_input_multiplier),context_output_multiplier:n(e.context_output_multiplier),speed_cost_multiplier:n(e.speed_cost_multiplier),standard_cost_usd:n(e.standard_cost_usd),speed_uplift_usd:n(e.speed_uplift_usd),input_cost_usd:n(e.input_cost_usd),cached_input_cost_usd:n(e.cached_input_cost_usd),output_cost_usd:n(e.output_cost_usd),reasoning_cost_usd:n(e.reasoning_cost_usd),fx_rate:u,estimated_usd:l,estimated_brl:m,recorded_usd:d,recorded_brl:p,recorded_fx_rate:f,coverage:{events:0,tokens:0,usd:0,brl:0},artifact_path:`.agents/records/runs/${r}`}}function it(e,t){let n=t.totals,r=e=>K(n?.[e]);return{data_source:`lifecycle_daily_read_models`,snapshot_id:null,source_latest_at:null,kind:e,offset:t.offset,limit:t.limit,total:t.total_count,has_more:t.has_more,next_cursor:null,subtotal:{entity_count:typeof n?.entity_count==`number`?n.entity_count:t.total_count,run_count:r(`invocation_count`),metrics:{duration:r(`total_duration`),total_tokens:r(`total_tokens`),cost_brl:r(`total_cost_brl`),cost_usd:r(`total_cost_usd`)}},rows:t.rows.map(t=>({id:String(t.task_id??t.spec_id??t.prd_id??t.execution_id??t.conversation_id??t.id??`unavailable`),title:String(t.title??t.task_id??t.spec_id??t.prd_id??t.execution_id??t.conversation_id??`Unavailable`),kind:e===`tasks`?`task`:e===`specs`?`spec`:e===`prds`?`prd`:e===`executions`?`execution`:`conversation`,status:typeof t.status==`string`?t.status:null,risk:typeof t.risk==`string`?t.risk:null,occurred_at:typeof t.occurred_at==`string`?t.occurred_at:typeof t.started_at==`string`?t.started_at:typeof t.last_day==`string`?`${t.last_day}T12:00:00.000Z`:``,parent_id:null,run_count:Number(t.invocation_count??0),cost_currency:`BRL`,metrics:{duration:K(t.total_duration),total_tokens:K(t.total_tokens),cost:K(t.total_cost_brl)}}))}}function at(e){return{loadCostDetail:(0,m.useCallback)(async()=>{throw Error(`SQLite Cost Monitor loads the selected paginated view; full detail is disabled.`)},[]),loadCostReadModelPage:(0,m.useCallback)(async({filters:t,from:n,kind:r,limit:i,offset:a,query:o,signal:s,to:c})=>{let l={tasks:`cost_monitor_tasks`,specs:`cost_monitor_specs`,prds:`cost_monitor_prds`,executions:`cost_monitor_executions`,conversations:`cost_monitor_conversations`}[r];return it(r,await e.sqliteViewPage(l,n===void 0||c===void 0?void 0:{from:n,to:c},{offset:a,limit:i,...t.query||o?{query:t.query||o}:{},...t.provider?{provider:t.provider}:{},...t.model?{model:t.model}:{},...t.agent?{agent:t.agent}:{},...t.phase?{phase:t.phase}:{},...t.status?{status:t.status}:{},...t.origin?{origin:t.origin}:{},...t.workType?{workType:t.workType}:{},...t.priority?{priority:t.priority}:{},...t.risk?{risk:t.risk}:{}},s))},[e]),loadCostRunPage:(0,m.useCallback)(t=>nt(e,t),[e]),loadCostGroupPage:(0,m.useCallback)(t=>tt(e,t),[e])}}function ot(e,t){return!1}function st(e,t=window,n=0){let r=!1,i=!1,a=new AbortController,o=t.setTimeout(()=>{r||i||(i=!0,e(a.signal))},n);return()=>{r||(r=!0,a.abort(),t.clearTimeout(o))}}var ct=2e3,lt=5e3,ut=1e4,dt=3e4,ft=`A atualização do snapshot não foi concluída. Os dados exibidos podem estar desatualizados.`;function pt(e,t){return e&&t<90}function mt(e,t){return e===`visible`?lt:t>0?dt:ut}function ht(e,t){return e!==null&&typeof t==`string`&&t.length>0&&e!==t}function gt(e,t){return(e===`current`||e===`updating`)&&typeof t==`string`&&t.length>0}function _t({observedRevision:e,pendingRevision:t,requestedRevision:n,succeeded:r}){return r?{observedRevision:n,pendingRevision:t===n?null:t}:{observedRevision:e,pendingRevision:t}}function vt({inFlight:e,lastRefreshAt:t,now:n,visibilityState:r}){return r===`visible`&&!e&&n-t>=5e3}function yt({api:e,costLocale:t,currency:n,dashboardView:r,loadOperationsDetails:i,operations:a,operationsDetailAbortRef:o,operationsDetailCancelRef:s,operationsPageAbortRef:c,pathname:l,pricing:u,refresh:d,refreshVersion:f,snapshotUpdating:p,setSnapshotUpdating:h,setError:g,setFxRate:_,setPathname:v,setPricing:y}){let b=(0,m.useRef)(!1),x=(0,m.useRef)(0),S=(0,m.useRef)(null),C=(0,m.useRef)(!1),w=(0,m.useRef)(null);(0,m.useEffect)(()=>(d(),()=>{s.current?.(),s.current=null,o.current?.abort(),o.current=null,c.current?.abort(),c.current=null,++f.current}),[o,s,c,d,f]),(0,m.useEffect)(()=>{let e=()=>{let e=Date.now();vt({inFlight:b.current,lastRefreshAt:x.current,now:e,visibilityState:document.visibilityState})&&(x.current=e,b.current=!0,d(!1,!1,!0).finally(()=>{b.current=!1}))};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[d]),(0,m.useEffect)(()=>{if(!p)return;let t=!1,n=0,r=null,i=async()=>{if(!(t||!pt(!0,n))){n+=1;try{let n=await e.ready();if(t)return;if(n.snapshot_state===`current`){h(!1),await d(!1,!1,!1,!0);return}}catch{}if(!t){if(pt(!0,n)){r=window.setTimeout(()=>void i(),ct);return}h(!1),g(ft)}}};return i(),()=>{t=!0,r!==null&&window.clearTimeout(r)}},[e,d,g,h,p]),(0,m.useEffect)(()=>{let t=!1,n=0,r=null,i=()=>{if(t||C.current)return;let e=w.current;e!==null&&(C.current=!0,d(!1,!1,!1,!0).then(t=>{t&&h(!1);let n=_t({observedRevision:S.current,pendingRevision:w.current,requestedRevision:e,succeeded:t});S.current=n.observedRevision,w.current=n.pendingRevision}).finally(()=>{C.current=!1,w.current!==e&&i()}))},a=async()=>{try{let r=await e.ready();if(t)return;n=0;let a=S.current;gt(r.snapshot_state,r.snapshot_revision)&&(a===null&&(S.current=r.snapshot_revision),ht(a,r.snapshot_revision)&&(w.current=r.snapshot_revision,i()))}catch{n+=1}t||(r=window.setTimeout(()=>void a(),mt(document.visibilityState,n)))};return a(),()=>{t=!0,r!==null&&window.clearTimeout(r)}},[e,d,h]),(0,m.useEffect)(()=>{if(!ot(r,a?.summary.overview_metrics?.partial===!0))return;let e=st(async e=>{await i(e)});return s.current=e,()=>{s.current===e&&(s.current=null),e()}},[r,i,a?.summary.overview_metrics?.partial,s]),(0,m.useEffect)(()=>window.localStorage.setItem(De,t),[t]),(0,m.useEffect)(()=>window.localStorage.setItem(Oe,n),[n]),(0,m.useEffect)(()=>{[`/`,`/setup-pricing`,`/setup-project`].includes(window.location.pathname)||(window.history.replaceState(null,``,`/${window.location.search}${window.location.hash}`),v(`/`))},[v]),(0,m.useEffect)(()=>{let e=()=>v(window.location.pathname);return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[v]),(0,m.useEffect)(()=>{l!==`/setup-pricing`||u!==null||Promise.all([e.pricing(),e.fxRate()]).then(([e,t])=>{y(e),_(t)}).catch(e=>g(String(e)))},[e,l,u,g,_,y])}var q={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 bt(e,t,n){let r=e=>e===`intake`||e===`orchestration`||e===`execution`||e===`review`||e===`audit`||e===`finalization`?e:`execution`,i=n.rows.map(e=>({id:e.id,artifact_path:`.agents/records/runs/${e.id}`,status:e.status===`running`||e.status===`failed`||e.status===`cancelled`?e.status:`completed`,phase:e.phase??`execution`,entrypoint:e.conversation_id===null?`task`:`conversation`,work_type:`new`,run_role:e.run_kind===`subrun`?`subagent`:`orchestrator`,run_kind:e.run_kind??`run`,run_purpose:r(e.run_purpose),requires_finalizer:!1,parent_run_id:e.parent_run_id,client:e.client??`unknown`,agent:e.agent??`unknown`,agent_name:e.agent??`unknown`,agent_persona:e.agent_persona??null,agent_job:e.agent_job??null,provider:e.provider??null,model:e.model??`unknown`,reasoning_effort:e.reasoning_effort??null,effective_model:e.model??null,effective_reasoning_effort:e.reasoning_effort??null,effective_config_mixed:e.pricing_mixed??!1,service_tier:e.service_tier??null,call_count:e.llm_call_count??null,terminal_call_count:null,failed_call_count:null,cancelled_call_count:null,conversation_id:e.conversation_id??e.id,execution_id:e.execution_id,task_id:e.task_id,spec_id:null,prd_id:null,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===void 0?e.duration_ms:e.source_duration_ms,duration_provenance:e.duration_provenance===`observed`||e.duration_provenance===`reconciled`||e.duration_provenance===`legacy_inferred`||e.duration_provenance===`estimated`?e.duration_provenance:`unavailable`,llm_call_count:e.llm_call_count??null,input_tokens:e.input_tokens??null,cached_input_tokens:e.cached_input_tokens??null,uncached_input_tokens:e.uncached_input_tokens??null,output_tokens:e.output_tokens??null,reasoning_tokens:e.reasoning_tokens??null,visible_output_tokens:e.visible_output_tokens??null,input_rate_usd_per_million:e.input_rate_usd_per_million??null,cached_input_rate_usd_per_million:e.cached_input_rate_usd_per_million??null,output_rate_usd_per_million:e.output_rate_usd_per_million??null,reasoning_rate_usd_per_million:e.reasoning_rate_usd_per_million??null,context_input_multiplier:e.context_input_multiplier??null,context_output_multiplier:e.context_output_multiplier??null,speed_cost_multiplier:e.speed_cost_multiplier??null,pricing_scenario:e.pricing_scenario??null,standard_cost_usd:e.standard_cost_usd??null,speed_uplift_usd:e.speed_uplift_usd??null,input_cost_usd:e.input_cost_usd??null,cached_input_cost_usd:e.cached_input_cost_usd??null,output_cost_usd:e.output_cost_usd??null,reasoning_cost_usd:e.reasoning_cost_usd??null,calculated_cost_usd:e.calculated_cost_usd??null,recorded_cost_usd:e.recorded_cost_usd??null,cost_variance_usd:e.cost_variance_usd??null,cost_usd:e.cost_usd??null,cost_brl:e.currency===`BRL`?e.cost:null,fx_rate:e.fx_rate??null,pricing_segment_count:e.pricing_segment_count??null,pricing_mixed:e.pricing_mixed??!1,pricing_model:e.pricing_model??null,pricing_source:e.pricing_source??null,...e.lifecycle_elapsed_ms===void 0?{}:{lifecycle_elapsed_ms:e.lifecycle_elapsed_ms},usage:{conversation:q,planning:q,execution:{...q,events:e.llm_call_count??0,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:e.cost_usd??null,brl:e.currency===`BRL`?e.cost:null}},total:{...q,events:e.llm_call_count??0,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:e.cost_usd??null,brl:e.currency===`BRL`?e.cost:null}},new_work:q,rework:q}}));return{...e,runs:i,executions:t===`executions`||t===`conversations`?n.rows.map((e,n)=>{let r=i[n];if(r===void 0)throw Error(`Operations entity page must have a projected run for every row.`);let a=r.execution_id??r.conversation_id,o=e.status??`unavailable`;return{id:a,kind:t===`conversations`?`interaction`:`delivery`,created_at:r.started_at,status:o,work_status:o,origin:t===`conversations`?{type:`interaction`,conversation_id:r.conversation_id}:{type:`task`,task_id:r.task_id??`unavailable`},dag:{nodes:[],topological_order:[]},result:null,artifact_path:`.agents/records/executions/${a}`,agent_call_count:0,orchestrator_run_count:0,subagent_run_count:0,finalizer_run_count:0,finalized_task_count:0,llm_call_count:0,llm_call_count_complete:!1,task_count:0,spec_count:0,prd_count:0,duration_ms:r.source_duration_ms??null,...e.lifecycle_elapsed_ms===void 0?{}:{lifecycle_elapsed_ms:e.lifecycle_elapsed_ms},total_tokens:r.usage.total.tokens.total,cost_brl:r.usage.total.cost.brl}}):e.executions}}function J(e){if(typeof e!=`string`)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function xt({api:e,entityFiltersRef:t,operationsPageAbortRef:n,operationsPageRequestVersionRef:r,operationsPeriod:i,operationsPeriodRef:a,refreshVersion:o,setEntityPage:s,setEntityPageKind:c,setOperations:l}){return{loadOperationsEntityPage:(0,m.useCallback)(async(u,d=0,f=t.current)=>{n.current?.abort();let p=new AbortController;n.current=p;let m=++r.current,h=o.current,g=R(i),_=()=>O(m,r.current,p.signal)&&T(h,o.current,g,R(a.current));c(u),s({offset:d,total:null,loading:!0,error:null});try{let t={runs:`operations_agent_invocations`,executions:`operations_executions`,conversations:`operations_conversations`}[u],n=await e.sqliteViewPage(t,g,{offset:d,limit:100,...f.query?{query:f.query}:{},...f.status?{status:f.status}:{},...f.risk?{risk:f.risk}:{}},p.signal),r={kind:u,offset:n.offset,limit:n.limit,total:n.total_count,aggregation:`canonical_entity`,rows:n.rows.map(e=>({id:String(e.agent_invocation_id??e.execution_id??e.conversation_id??e.id),started_at:String(e.occurred_at??e.started_at??`1970-01-01T00:00:00.000Z`),finished_at:typeof e.finished_at==`string`?e.finished_at:null,task_id:typeof e.task_id==`string`?e.task_id:null,execution_id:typeof e.execution_id==`string`?e.execution_id:null,conversation_id:typeof e.conversation_id==`string`?e.conversation_id:null,parent_run_id:typeof e.parent_agent_invocation_id==`string`?e.parent_agent_invocation_id:null,run_kind:e.invocation_kind===`delegated`||e.invocation_kind===`subagent`?`subrun`:e.invocation_kind===`orchestrator`?`run`:null,run_purpose:typeof e.purpose==`string`?e.purpose:null,phase:typeof e.phase==`string`?e.phase:null,status:typeof e.status==`string`?e.status:null,agent:typeof e.zaip_agent==`string`?e.zaip_agent:null,agent_persona:typeof e.zaip_agent_persona==`string`?e.zaip_agent_persona:null,agent_job:typeof e.zaip_agent_job==`string`?e.zaip_agent_job:null,client:typeof e.client==`string`?e.client:null,provider:typeof e.provider==`string`?e.provider:null,model:typeof e.model==`string`?e.model:null,reasoning_effort:typeof e.reasoning_effort==`string`?e.reasoning_effort:null,service_tier:typeof e.service_tier==`string`?e.service_tier:null,duration_ms:typeof e.duration_ms==`number`?e.duration_ms:typeof e.total_duration==`number`?e.total_duration:null,source_duration_ms:typeof e.source_duration_ms==`number`?e.source_duration_ms:null,duration_provenance:typeof e.duration_provenance==`string`?e.duration_provenance:null,llm_call_count:typeof e.llm_call_count==`number`?e.llm_call_count:null,input_tokens:typeof e.input_tokens==`number`?e.input_tokens:null,cached_input_tokens:typeof e.cached_input_tokens==`number`?e.cached_input_tokens:null,uncached_input_tokens:typeof e.uncached_input_tokens==`number`?e.uncached_input_tokens:null,output_tokens:typeof e.output_tokens==`number`?e.output_tokens:null,reasoning_tokens:typeof e.reasoning_tokens==`number`?e.reasoning_tokens:null,visible_output_tokens:typeof e.visible_output_tokens==`number`?e.visible_output_tokens:null,total_tokens:typeof e.total_tokens==`number`?e.total_tokens:null,input_rate_usd_per_million:typeof e.input_rate_usd_per_million==`number`?e.input_rate_usd_per_million:null,cached_input_rate_usd_per_million:typeof e.cached_input_rate_usd_per_million==`number`?e.cached_input_rate_usd_per_million:null,output_rate_usd_per_million:typeof e.output_rate_usd_per_million==`number`?e.output_rate_usd_per_million:null,reasoning_rate_usd_per_million:typeof e.reasoning_rate_usd_per_million==`number`?e.reasoning_rate_usd_per_million:null,context_input_multiplier:typeof e.context_input_multiplier==`number`?e.context_input_multiplier:null,context_output_multiplier:typeof e.context_output_multiplier==`number`?e.context_output_multiplier:null,speed_cost_multiplier:typeof e.speed_cost_multiplier==`number`?e.speed_cost_multiplier:null,pricing_scenario:typeof e.pricing_scenario==`string`?e.pricing_scenario:null,standard_cost_usd:typeof e.standard_cost_usd==`number`?e.standard_cost_usd:null,speed_uplift_usd:typeof e.speed_uplift_usd==`number`?e.speed_uplift_usd:null,input_cost_usd:typeof e.input_cost_usd==`number`?e.input_cost_usd:null,cached_input_cost_usd:typeof e.cached_input_cost_usd==`number`?e.cached_input_cost_usd:null,output_cost_usd:typeof e.output_cost_usd==`number`?e.output_cost_usd:null,reasoning_cost_usd:typeof e.reasoning_cost_usd==`number`?e.reasoning_cost_usd:null,calculated_cost_usd:typeof e.calculated_cost_usd==`number`?e.calculated_cost_usd:null,recorded_cost_usd:typeof e.recorded_cost_usd==`number`?e.recorded_cost_usd:null,cost_variance_usd:typeof e.cost_variance_usd==`number`?e.cost_variance_usd:null,cost_usd:typeof e.cost_usd==`number`?e.cost_usd:null,fx_rate:typeof e.fx_rate==`number`?e.fx_rate:null,pricing_segment_count:typeof e.pricing_segment_count==`number`?e.pricing_segment_count:null,pricing_mixed:e.pricing_mixed===1||e.pricing_mixed===!0,pricing_model:typeof e.audit_pricing_model==`string`?e.audit_pricing_model:typeof e.pricing_model==`string`?e.pricing_model:null,pricing_source:typeof e.audit_pricing_source==`string`?e.audit_pricing_source:typeof e.pricing_source==`string`?e.pricing_source:null,cost:typeof e.total_cost_brl==`number`?e.total_cost_brl:typeof e.cost_brl==`number`?e.cost_brl:null,currency:`BRL`}))};if(!_())return;l(e=>e===null?e:bt(e,u,r)),s({offset:r.offset,total:r.total,loading:!1,error:null,aggregation:r.aggregation})}catch(e){if(!_()||E(e))return;s({offset:d,total:null,loading:!1,error:e instanceof Error?e.message:String(e)})}finally{n.current===p&&(n.current=null)}},[e,t,n,r,i,a,o,s,c,l]),loadOperationsLifecyclePage:(0,m.useCallback)(async(u,d=0,f=t.current)=>{n.current?.abort();let p=new AbortController;n.current=p;let m=++r.current,h=o.current,g=R(i),_=()=>O(m,r.current,p.signal)&&T(h,o.current,g,R(a.current));c(u),s({offset:d,total:null,loading:!0,error:null});try{let t=await e.sqliteViewPage(u===`changes`?`operations_changes`:`operations_decisions`,g,{offset:d,limit:100,...f.query?{query:f.query}:{},...f.status?{status:f.status}:{},...f.risk?{risk:f.risk}:{}},p.signal),n=u===`changes`?t.rows.map(e=>{let t=String(e.source_type),n=String(e.source_id);return{id:String(e.id),title:typeof e.title==`string`?e.title:String(e.id),created_at:typeof e.occurred_at==`string`?e.occurred_at:null,status:typeof e.status==`string`?e.status:`unclassified`,risk:typeof e.risk==`string`?e.risk:`unclassified`,source:t===`spec`?{type:`spec`,spec_id:n}:t===`prd`?{type:`prd`,prd_id:n,spec_id:null}:{type:`task`,task_id:n},requirement_ids:J(e.requirement_ids_json),acceptance_ids:J(e.acceptance_ids_json),task_ids:J(e.task_ids_json),result:typeof e.result==`string`?e.result:null,artifact_path:typeof e.source_path==`string`?e.source_path:String(e.id)}}):t.rows.map(e=>({id:String(e.id),title:typeof e.title==`string`?e.title:String(e.id),origin:e.origin===`human`?`human`:`agent`,scope_type:e.scope_type===`execution`?`execution`:`change`,scope_id:String(e.scope_id),artifact_path:typeof e.source_path==`string`?e.source_path:String(e.id),created_at:typeof e.occurred_at==`string`?e.occurred_at:`1970-01-01T00:00:00.000Z`})),r={kind:u,offset:t.offset,limit:t.limit,total:t.total_count,rows:n};if(!_())return;l(e=>e===null?e:{...e,...u===`changes`?{changes:r.rows}:{decisions:r.rows}}),s({offset:r.offset,total:r.total,loading:!1,error:null})}catch(e){if(!_()||E(e))return;s({offset:d,total:null,loading:!1,error:e instanceof Error?e.message:String(e)})}finally{n.current===p&&(n.current=null)}},[e,t,n,r,i,a,o,s,c,l])}}function St({api:e,operations:t,setError:n,setFailedArea:r,setLoadingArea:i}){let[a,o]=(0,m.useState)(null),[s,c]=(0,m.useState)([]),[l,u]=(0,m.useState)(null),[d,f]=(0,m.useState)(null),p=(0,m.useRef)(0),h=(0,m.useRef)(0),g=(0,m.useRef)(null),[_,v]=(0,m.useState)(null),[y,b]=(0,m.useState)(``);async function x(a){let c=++h.current;g.current?.abort();let l=new AbortController;g.current=l,n(null),r(null),o(null),v(a),i(`traceability`),await new Promise(e=>window.requestAnimationFrame(()=>e()));try{let n=await e.taskTrace(a,l.signal);if(h.current!==c)return!1;let r=s.find(e=>e.id===a)??t?.tasks.find(e=>e.id===a);return o({...n,task_title:r?.title||n.task_title||a,task_risk:r?.risk||n.task_risk||null,task_created_at:r?.created_at||n.task_created_at||null,task_progress:n.task_progress??r?.progress??0}),!0}catch(e){return l.signal.aborted||h.current!==c?!1:(n(e instanceof Error?e.message:String(e)),r(`traceability`),!1)}finally{h.current===c&&(g.current===l&&(g.current=null),v(null),i(e=>e===`traceability`?null:e))}}function S(e){let n=t?.changes.find(t=>t.id===e);n!==void 0&&(o(null),f({kind:`change`,row:n}))}function C(e,n){let r=(e===`PRD`?t?.prds:t?.specs)?.find(e=>e.id===n);r!==void 0&&(o(null),f({kind:`macro`,label:e,row:r}))}async function w(n,r){let i=(n===`prd`?t?.prds:t?.specs)?.find(e=>e.id===r);if(!i)return;let a=++p.current,o=n===`prd`?`PRD`:`SPEC`;u({kind:n,label:o,preview:i});try{let t=n===`prd`?await e.prd(r):await e.spec(r);if(p.current!==a)return;u({kind:n,label:o,preview:i,detail:t})}catch(e){if(p.current!==a)return;u({kind:n,label:o,preview:i,error:e instanceof Error?e.message:String(e)})}}function T(){p.current+=1,u(null)}return{closeDocument:T,documentDetail:l,openDocument:w,openTrace:x,openTraceChange:S,openTraceMacro:C,selectedTraceTaskId:y,setSelectedTraceTaskId:b,setTrace:o,setTraceLink:f,setTraceLoadingTaskId:v,setTraceTasks:c,trace:a,traceLink:d,traceLoadingTaskId:_,traceTasks:s}}function Ct({cursor:e,page:t,tasks:n}){let r=new Map(n.map(e=>[e.id,e]));for(let e of t.tasks)r.set(e.id,e);let i=e.offset+t.tasks.length;return{tasks:[...r.values()],cursor:t.tasks.length===0||i>=t.total?{offset:0,stageIndex:e.stageIndex+1}:{...e,offset:i}}}function wt(e,t,n){return Math.min(t,e+n)}function Tt(e,t,n){let r=(0,m.useRef)(t),i=(0,m.useRef)({offset:0,stageIndex:0}),a=(0,m.useRef)(!1),[o,s]=(0,m.useState)(!1),[c,l]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{r.current=t},[t]),{loadMoreTraceTasks:(0,m.useCallback)(async(t=!1,o=!1)=>{if(a.current||(o&&(i.current={offset:0,stageIndex:0},r.current=[],n([]),s(!0)),i.current.stageIndex>=1))return r.current;a.current=!0,l(!0);try{do{let a=i.current,o=await e.traceabilityTasks(a.offset,10),s=Ct({cursor:a,page:o,tasks:r.current});if(r.current=s.tasks,n(r.current),i.current=s.cursor,o.tasks.length>0&&!t)break}while(i.current.stageIndex<1);return s(i.current.stageIndex<1),r.current}finally{a.current=!1,l(!1)}},[e,n]),traceTasksHasMore:o,traceTasksLoading:c}}function Et({api:e,boardAbortControllersRef:t,boardFilterKeyRef:n,boardFiltersRef:r,boardInFlightRef:i,boardInitialPageRef:a,boardLoadedRef:o,boardRequestVersionRef:s,dashboardView:c,operations:l,operationsPeriod:u,operationsPeriodRef:d,overviewStatusInFlightRef:f,quickOverviewMetricsRef:p,setBoardKindTotals:h,setBoardStates:g,setBoardTotals:_,setOperations:v,setOverviewClassificationPages:y,setOverviewStatusPages:b}){let x=(0,m.useCallback)(()=>{s.current+=1;for(let e of t.current.values())e.abort();t.current.clear(),i.current.clear(),a.current.clear(),o.current={},_({}),h({}),g({}),b({}),y({})},[t,i,a,o,s,h,g,_,y,b]),S=(0,m.useCallback)(async n=>{if(l===null||i.current.has(n))return;i.current.add(n),t.current.get(n)?.abort();let a=new AbortController;t.current.set(n,a);let c=s.current,f=R(u);g(e=>({...e,[n]:{loading:!0,error:null}}));let p=o.current[n]??0;try{let t=await e.operationsBoard(f,n,p,r.current,a.signal,10);if(a.signal.aborted||c!==s.current||f.from!==R(d.current).from||f.to!==R(d.current).to)return;v(e=>e===null?e:{...k(e,[t]),summary:e.summary}),_(e=>({...e,[n]:t.total})),h(e=>({...e,[n]:t.totals_by_kind})),o.current={...o.current,[n]:p+t.prds.length+t.specs.length+t.tasks.length}}catch(e){if(a.signal.aborted||c!==s.current||E(e))return;g(t=>({...t,[n]:{loading:!1,error:e instanceof Error?e.message:String(e)}}))}finally{c===s.current&&(i.current.delete(n),t.current.get(n)===a&&t.current.delete(n),g(e=>e[n]?.error===null?{...e,[n]:{loading:!1,error:null}}:e))}},[e,t,r,i,o,s,l,u,d,h,g,_,v]),C=(0,m.useCallback)(e=>{let t={...e,kind:e.kind??r.current.kind??``},i=`${t.query}|${t.status}|${t.risk}|${t.origin??``}|${t.kind}`;i!==n.current&&(n.current=i,r.current=t,x(),v(e=>e===null?e:{...e,prds:[],specs:[],tasks:[],changes:[],summary:i===`||||`&&p.current!==void 0?{...e.summary,overview_metrics:p.current}:e.summary}))},[n,r,p,x,v]),w=(0,m.useCallback)(async(t,n,r)=>{let i=Ce(t,n),a=f.current;if(a.has(i))return;a.add(i);let o=s.current,c=R(u);b(e=>({...e,[i]:{items:r===0?[]:e[i]?.items??[],total:e[i]?.total??0,loading:!0,error:null}}));try{let a=await e.operationsBoard(c,t,r,{kind:n===`task`?`all-tasks`:n});if(o!==s.current||c.from!==R(d.current).from||c.to!==R(d.current).to)return;let l=n===`task`?a.tasks:n===`spec`?a.specs:a.prds;b(e=>({...e,[i]:{items:r===0?l:[...e[i]?.items??[],...l],total:a.total,loading:!1,error:null}}))}catch(e){if(o!==s.current||E(e))return;b(t=>({...t,[i]:{items:t[i]?.items??[],total:t[i]?.total??0,loading:!1,error:e instanceof Error?e.message:String(e)}}))}finally{a.delete(i)}},[e,s,u,d,f,b]),T=(0,m.useCallback)(async(t,n,r)=>{let i=we(t,n),a=f.current;if(a.has(i))return;a.add(i);let o=s.current,c=R(u);y(e=>({...e,[i]:{items:r===0?[]:e[i]?.items??[],total:e[i]?.total??0,loading:!0,error:null}}));try{let a=await e.operationsClassification(c,t,n,r);if(o!==s.current||c.from!==R(d.current).from||c.to!==R(d.current).to)return;let l=t===`task`?a.tasks:t===`spec`?a.specs:a.prds;y(e=>({...e,[i]:{items:r===0?l:[...e[i]?.items??[],...l],total:a.total,loading:!1,error:null}}))}catch(e){if(o!==s.current||E(e))return;y(t=>({...t,[i]:{items:t[i]?.items??[],total:t[i]?.total??0,loading:!1,error:e instanceof Error?e.message:String(e)}}))}finally{a.delete(i)}},[e,s,u,d,f,y]),D=(0,m.useCallback)(t=>{let n={...r.current,...t},i=R(u);return{prepare:async()=>{let t=await Promise.all(Te.map(t=>e.operationsBoard(i,t,0,n))),r=e=>[...e.prds.map(({kind:e,...t})=>({kind:`prd`,...t})),...e.specs.map(({kind:e,...t})=>({kind:`spec`,...t})),...e.tasks.map(e=>({kind:`task`,...e}))];return{totalRows:t.reduce((e,t)=>e+t.total,0),pages:async function*(){for(let a of t){let t=a,o=0;for(;;){let a=r(t);if(a.length===0||(o+=a.length,yield a,o>=t.total))break;t=await e.operationsBoard(i,t.stage,o,n)}}}}}}},[e,r,u]);return(0,m.useEffect)(()=>{if(c!==`operations`||l===null)return;let e=!1,t=s.current,n=()=>!e&&t===s.current,r=async()=>{if(!n())return;let e=Te.filter(e=>!a.current.has(e)&&!i.current.has(e));for(let t=0;t<e.length&&n();t+=3){let r=e.slice(t,t+3);if(!n())return;for(let e of r)a.current.add(e);await Promise.all(r.map(e=>S(e)))}},o=window.setTimeout(()=>void r(),0);return()=>{e=!0,window.clearTimeout(o)}},[i,a,s,c,S,l]),{boardExportSource:D,loadFilteredBoard:C,loadMoreBoard:S,loadOverviewClassificationPage:T,loadOverviewStatusPage:w,resetBoard:x}}function Y(e,t){return JSON.stringify([e.query,e.status,e.risk,e.origin??``,e.kind??``,t.from??``,t.to??``])}function Dt(e,t,n){return e===`explicit`||t!==n}function X(e,t){return{...e,kind:e.kind??t.kind??``}}var Z={offset:0,limit:10,total:null,hasMore:!1,typeFilter:`all`,rows:[],loading:!1,error:null};function Ot({api:e,operationsPeriod:t,operationsPeriodRef:n}){let[r,i]=(0,m.useState)(Z),a=(0,m.useRef)({query:``,status:``,risk:``}),o=(0,m.useRef)(null),s=(0,m.useRef)(0),c=(0,m.useRef)(null),l=(0,m.useCallback)(async(r,l=0,u=`explicit`)=>{let d=R(t),f=X(r,a.current),p=Y(f,d);if(!Dt(u,p,c.current))return;o.current?.abort();let m=new AbortController;o.current=m;let h=++s.current;a.current=f,c.current=p;let g=f.kind||`all`;i(e=>({...e,offset:l,typeFilter:g,loading:!0,error:null}));try{let t=await e.sqliteViewPage(`operations_work_list`,d,{offset:l,limit:10,...f.query?{query:f.query}:{},...f.status?{status:f.status}:{},...f.risk?{risk:f.risk}:{},...f.origin?{origin:f.origin}:{},...g===`all`?{}:{kind:g}},m.signal);if(m.signal.aborted||h!==s.current||d.from!==R(n.current).from||d.to!==R(n.current).to)return;i({offset:t.offset,limit:t.limit,total:t.total_count,hasMore:t.has_more,typeFilter:g,rows:t.rows,loading:!1,error:null})}catch(e){if(m.signal.aborted||h!==s.current)return;c.current===p&&(c.current=null),i(t=>({...t,offset:l,typeFilter:g,loading:!1,error:e instanceof Error?e.message:String(e)}))}finally{o.current===m&&(o.current=null)}},[e,t,n]),u=(0,m.useCallback)(()=>{o.current?.abort(),o.current=null,++s.current,c.current=null,i(Z)},[]);return{workListPage:r,workListFiltersRef:a,loadWorkListFilters:(0,m.useCallback)(e=>l(e,0,`filter-hydration`),[l]),loadWorkListPage:l,resetWorkListPage:u}}async function*kt(e,t){let n=e;for(;;){if(n.rows.length===0)return;yield n.rows;let e=n.offset+n.rows.length;if(!n.has_more||e>=n.total_count)return;n=await t(e)}}function At({api:e,operationsPeriod:t}){return(0,m.useCallback)((n,r)=>{let i=R(t);if(n===`work-kanban`)return;let a={"work-list":`operations_work_list`,changes:`operations_changes`,decisions:`operations_decisions`,executions:`operations_executions`,runs:`operations_agent_invocations`,conversations:`operations_conversations`,daily:`operations_daily`,monthly:`operations_monthly`,yearly:`operations_annual`}[n];if(a===void 0)return;let o=e=>({offset:e,limit:100,...r.query?{query:r.query}:{},...r.status?{status:r.status}:{},...r.risk?{risk:r.risk}:{},...r.origin?{origin:r.origin}:{},...a===`operations_work_list`&&r.kind?{kind:r.kind}:{}});return{prepare:async()=>{let t=await e.sqliteViewPage(a,i,o(0));return{totalRows:t.total_count,pages:()=>kt(t,t=>e.sqliteViewPage(a,i,o(t)))}}}},[e,t])}var jt=1500;function Q({snapshotUpdating:e,initialDataPending:t,dismissed:n,delayElapsed:r}){return e&&t&&!n&&r}function Mt(e,t,n){let[r,i]=(0,m.useState)(!1),[a,o]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{if(!e||!t||r){o(!1);return}let n=window.setTimeout(()=>o(!0),jt);return()=>window.clearTimeout(n)},[t,r,e]),Q({snapshotUpdating:e,initialDataPending:t,dismissed:r,delayElapsed:a})?(0,g.jsxs)(`div`,{"aria-live":`polite`,className:`app-notice app-snapshot-status`,role:`status`,children:[(0,g.jsx)(`span`,{children:`Exibindo o último snapshot local validado. Os dados canônicos estão sendo atualizados em segundo plano e estarão atuais na próxima abertura.`}),(0,g.jsx)(`button`,{"aria-label":n===`pt-BR`?`Fechar aviso de atualização do snapshot`:`Dismiss snapshot update notice`,onClick:()=>i(!0),type:`button`,children:`×`})]}):null}function Nt(){Be(je());let[e,t]=(0,m.useState)(!1),n=(0,m.useMemo)(je,[]),r=(0,m.useMemo)(()=>new Me(n),[n]),{loadCostDetail:i,loadCostReadModelPage:a,loadCostRunPage:o,loadCostGroupPage:s}=at(r),[c,l]=(0,m.useState)(()=>Ae(window.location.pathname)),u=(0,m.useRef)(c);u.current=c;let[d,f]=(0,m.useState)(null),[p,h]=(0,m.useState)({offset:0,total:null,loading:!1,error:null}),[g,_]=(0,m.useState)(`runs`),v=(0,m.useRef)({query:``,status:``,risk:``}),[y,b]=(0,m.useState)({}),[x,O]=(0,m.useState)({}),[k,ee]=(0,m.useState)({}),[te,ne]=(0,m.useState)({}),[re,A]=(0,m.useState)({}),[j,M]=(0,m.useState)(null),[ie,N]=(0,m.useState)(null),[P,ae]=(0,m.useState)(ke),[F,oe]=(0,m.useState)(()=>window.localStorage.getItem(`zaip-dashboard-currency`)===`USD`?`USD`:`BRL`),se=(0,m.useRef)(F);se.current=F;let ce=(0,m.useCallback)(e=>{ae(e),oe(e===`en-US`?`USD`:`BRL`)},[]),[I,le]=(0,m.useState)(()=>be),ue=I.preset===`all`?null:I.range.start,de=I.preset===`all`?null:I.range.end,fe=(0,m.useMemo)(()=>({from:ue,to:de}),[ue,de]),L=(0,m.useRef)(I);L.current=I;let pe=(0,m.useRef)(null),[me,he]=(0,m.useState)(!1),[ge,_e]=(0,m.useState)(null),[ve,ye]=(0,m.useState)(null),[xe,Se]=(0,m.useState)(window.location.pathname),[Te,Ee]=(0,m.useState)(!0),[z,De]=(0,m.useState)(!1),[,Oe]=(0,m.useState)(!1),[,Ne]=(0,m.useState)(!1),[Pe,B]=(0,m.useState)(`operations`),[V,H]=(0,m.useState)(null),[Fe,U]=(0,m.useState)(null);(0,m.useEffect)(()=>{r.captureTelemetry().then(()=>r.ready()).then(e=>t(e.snapshot_state===`updating`)).catch(()=>{})},[r]);let[Le,W]=(0,m.useState)(null),[Re,ze]=(0,m.useState)(null),[G,K]=(0,m.useState)(null),[Qe,$e]=(0,m.useState)(Ge),et=(0,m.useCallback)(e=>{$e(t=>Ke(t,e))},[]);(0,m.useEffect)(()=>{let e=!1;return r.dashboardIdentity().then(t=>{e||et(t)}).catch(()=>{}),()=>{e=!0}},[r,et]);let{closeDocument:tt,documentDetail:nt,openDocument:rt,openTrace:it,openTraceChange:ot,openTraceMacro:st,selectedTraceTaskId:ct,setSelectedTraceTaskId:lt,setTrace:ut,setTraceLink:dt,setTraceLoadingTaskId:ft,setTraceTasks:pt,trace:mt,traceLink:ht,traceLoadingTaskId:gt,traceTasks:_t}=St({api:r,operations:d,setError:W,setFailedArea:H,setLoadingArea:B}),{loadMoreTraceTasks:vt,traceTasksHasMore:q,traceTasksLoading:bt}=Tt(r,_t,pt),J=(0,m.useRef)(0),Ct=(0,m.useRef)(0),wt=(0,m.useRef)(!1),Y=(0,m.useRef)(0),Dt=(0,m.useRef)(0),X=(0,m.useRef)(null),Z=(0,m.useRef)(!1),kt=(0,m.useRef)(!1),jt=(0,m.useRef)(null),Q=(0,m.useRef)(null),Nt=(0,m.useRef)(null),Pt=(0,m.useRef)(0),Ft=(0,m.useRef)({}),It=(0,m.useRef)(new Set),Lt=(0,m.useRef)(new Map),Rt=(0,m.useRef)(new Set),zt=(0,m.useRef)(new Set),Bt=(0,m.useRef)({query:``,status:``,risk:``,origin:``,kind:``}),Vt=(0,m.useRef)(`||||`),Ht=(0,m.useRef)(0),Ut=(0,m.useRef)(void 0),{workListPage:Wt,workListFiltersRef:Gt,loadWorkListFilters:Kt,loadWorkListPage:qt,resetWorkListPage:Jt}=Ot({api:r,operationsPeriod:I,operationsPeriodRef:L}),Yt=(0,m.useRef)(!1),$=(0,m.useCallback)(async(e=!0,n=!1,i=!1,a=!1)=>{jt.current?.(),jt.current=null,Q.current?.abort(),Q.current=null,Ht.current+=1;for(let e of Lt.current.values())e.abort();Lt.current.clear(),It.current.clear(),zt.current.clear(),Ft.current={},b({}),O({}),ee({}),ne({}),A({});let o=++J.current,s=Ct.current,c=u.current,l=fe,d=()=>w(o,J.current)&&T(o,J.current,l,R(L.current));e&&(Ee(!0),B(`operations`)),W(null),H(null);try{if(n){let e=await r.reconcileOpenWork(F,l),n=Ie(e,d());if(ze(n.reconciliation),n.dismissProgressDialog&&U(null),!n.applySnapshotState)return!1;if(t(e.snapshot_state===`updating`),n.reloadQuickProjection){let e=await r.operations(l,`quick`,void 0,!0);if(!d())return!1;Yt.current=!1,f(e),Ut.current=e.summary.overview_metrics,kt.current=!1,K(e.summary.latest_token_collected_at??null)}}else if(i){let e=await r.refreshProjection(F,l);if(!d())return!1;f(e.operations),Ut.current=e.operations.summary.overview_metrics,kt.current=!0,M(e.costs),Z.current=!0,N(null);let t=e.dashboard;t&&$e(e=>Ke(e,t)),K(e.projection.latest_token_collected_at??null)}else{let[e,t]=await Promise.all([r.operations(l,`quick`,void 0,Yt.current),F===`USD`||a?r.costMonitor(F,l,`summary`):Promise.resolve(null)]);if(!d())return!1;Yt.current=!1,f(e),Ut.current=e.summary.overview_metrics,kt.current=!1,t!==null&&(M(t),Z.current=!1,N(null)),K(e.summary.latest_token_collected_at??null)}return!0}catch(e){return d()?(W(e instanceof Error?e.message:String(e)),H(c===`cost-monitor`?`costs`:`operations`),!1):!1}finally{d()&&D(s,Ct.current)&&Ne(!1),e&&d()&&(Ee(!1),B(e=>e===`operations`?null:e))}},[r,F,fe]),Xt=(0,m.useCallback)(async e=>{if(kt.current||wt.current||e?.aborted)return null;Q.current?.abort();let t=e===void 0?new AbortController:null,n=e??t?.signal;if(n===void 0)return null;t!==null&&(Q.current=t),wt.current=!0,Y.current+=1,B(`costs`),H(null);try{let e=++J.current,t=R(I),i=()=>w(e,J.current)&&T(e,J.current,t,R(L.current)),a=await r.operations(t,`detail`,n);return i()?(f(a),kt.current=!0,a):null}catch(e){return n.aborted||E(e)?null:(W(e instanceof Error?e.message:String(e)),H(`operations`),null)}finally{t!==null&&Q.current===t&&(Q.current=null),wt.current=!1,Y.current=Math.max(0,Y.current-1),Y.current===0&&B(e=>e===`costs`?null:e)}},[r,I]),{loadOperationsEntityPage:Zt,loadOperationsLifecyclePage:Qt}=xt({api:r,entityFiltersRef:v,operationsPageAbortRef:Nt,operationsPageRequestVersionRef:Pt,operationsPeriod:I,operationsPeriodRef:L,refreshVersion:J,setEntityPage:h,setEntityPageKind:_,setOperations:f}),$t=(0,m.useCallback)((e,t)=>{v.current=t,e===`changes`||e===`decisions`?Qt(e,0,t):Zt(e,0,t)},[Zt,Qt]),{boardExportSource:en,loadFilteredBoard:tn,loadMoreBoard:nn,loadOverviewClassificationPage:rn,loadOverviewStatusPage:an,resetBoard:on}=Et({api:r,boardAbortControllersRef:Lt,boardFilterKeyRef:Vt,boardFiltersRef:Bt,boardInFlightRef:It,boardInitialPageRef:zt,boardLoadedRef:Ft,boardRequestVersionRef:Ht,dashboardView:c,operations:d,operationsPeriod:I,operationsPeriodRef:L,overviewStatusInFlightRef:Rt,quickOverviewMetricsRef:Ut,setBoardKindTotals:O,setBoardStates:ee,setBoardTotals:b,setOperations:f,setOverviewClassificationPages:A,setOverviewStatusPages:ne}),sn=At({api:r,operationsPeriod:I}),cn=async e=>{e&&ze(null),U(e?`reconciling`:`refreshing`);try{await $(!1,e,!e)}finally{U(null)}};(0,m.useEffect)(()=>{let e=null,t=()=>{e=window.setTimeout(()=>{le(e=>{let t=Xe(e);return t!==e&&(pe.current=t),t}),t()},Ze())};return t(),()=>{e!==null&&window.clearTimeout(e)}},[]),(0,m.useEffect)(()=>{pe.current===I&&(pe.current=null,$(!1,!1,!0,!0))},[I,$]),yt({api:r,costLocale:P,currency:F,dashboardView:c,loadOperationsDetails:Xt,operations:d,operationsDetailAbortRef:Q,operationsDetailCancelRef:jt,operationsPageAbortRef:Nt,pathname:xe,pricing:ge,refresh:$,refreshVersion:J,setSnapshotUpdating:t,setError:W,setFxRate:ye,setPathname:Se,setPricing:_e,snapshotUpdating:e});let ln=He(Se),un=(0,m.useCallback)(async()=>{X.current?.abort();let e=new AbortController;X.current=e;let t=++Dt.current,n=R(I);Y.current+=1,B(`costs`),W(null),H(null);try{let i=await r.costMonitor(F,n,`summary`,e.signal),a=R(L.current);if(!C({aborted:e.signal.aborted,currentCurrency:se.current,currentPeriod:a,currentRequestVersion:Dt.current,requestVersion:t,requestedCurrency:F,requestedPeriod:n}))return;M(i),Z.current=!0,N(null)}catch(n){if(e.signal.aborted||t!==Dt.current)return;W(n instanceof Error?n.message:String(n)),H(`costs`)}finally{Y.current=Math.max(0,Y.current-1),Y.current===0&&B(e=>e===`costs`?null:e),X.current===e&&(X.current=null)}},[r,F,I]);(0,m.useEffect)(()=>{F!==`USD`||j?.currency===F||un()},[j?.currency,F,un]),(0,m.useEffect)(()=>{d===null||V===`costs`||X.current!==null||S({costsLoaded:Z.current,currency:F,snapshotCurrency:j?.currency})&&un()},[j?.currency,F,V,un,d]);let dn=Ye({setDashboardView:l,costsLoadedRef:Z,currency:F,costs:j,loadCostSummary:un,costSummaryAbortRef:X,traceTasks:_t,boardRequestVersionRef:Ht,loadMoreTraceTasks:vt,setTraceTasks:pt,setSelectedTraceTaskId:lt,openTrace:it,setTrace:ut,setTraceLoadingTaskId:ft}),fn=Ue(j,ie,F),{fact:pn,periods:mn}=We(j,ie,F),hn=()=>qe(V,ct,d,un,it,Xt,$,W),gn=Je(r,P,ve,ln,xe,ge,$,ye,_e);return{loadMoreBoard:nn,overviewStatusPageKey:Ce,overviewClassificationPageKey:we,boardRequestVersionRef:Ht,boardAbortControllersRef:Lt,boardInFlightRef:It,boardInitialPageRef:zt,boardLoadedRef:Ft,setBoardTotals:b,setBoardKindTotals:O,setBoardStates:ee,setOverviewStatusPages:ne,setOverviewClassificationPages:A,setOperationsLoading:Ee,operations:d,error:Le,globalLoadingPending:F===`USD`&&j?.currency!==F,costLocale:P,refresh:async()=>{await $()},snapshotNotice:Mt(e,d===null&&Te,P),setupRoute:gn,failedArea:V,retryLastLoad:hn,costs:j,currency:F,dashboardView:c,lastUpdatedAt:G,loadCostDetail:i,loadCostReadModelPage:a,loadCostRunPage:o,loadCostGroupPage:s,loadingArea:Pe,setDisplayedCosts:N,setCurrency:oe,setCostSurfaceLoading:Oe,changeDashboardLocale:ce,loadMoreTraceTasks:vt,openTrace:it,setRefreshDialog:U,setSelectedTraceTaskId:lt,openTraceChange:ot,openTraceMacro:st,selectedTraceTaskId:ct,trace:mt,traceLoadingTaskId:gt,traceTasksHasMore:q,traceTasksLoading:bt,traceTasks:_t,capabilityNavigation:Ve(c,P,e=>void dn(e)),boardTotals:y,boardKindTotals:x,boardExportSource:en,detailExportSource:sn,boardStates:k,operationsPeriod:I,entityPage:p,dashboardIdentity:Qe,operationsLoading:Te,factualCostFact:pn,factualCostPeriods:mn,setOperationsSurfaceLoading:De,operationsSurfaceLoading:z,currentCostByRun:fn,loadOperationsEntityPage:Zt,loadOperationsLifecyclePage:Qt,loadOperationsDetails:Xt,entityPageKind:g,loadFilteredOperationsPage:$t,loadFilteredBoard:tn,loadWorkListPage:qt,loadWorkListFilters:Kt,workListFiltersRef:Gt,boardFiltersRef:Bt,workListPage:Wt,overviewStatusPages:te,loadOverviewStatusPage:an,overviewClassificationPages:re,loadOverviewClassificationPage:rn,openDocument:rt,api:r,setError:W,operationsPeriodRef:L,setOperationsPeriod:le,operationsDetailLoadedRef:kt,operationsDetailCancelRef:jt,operationsDetailAbortRef:Q,operationsPageAbortRef:Nt,resetWorkListPage:Jt,operationsPageRequestVersionRef:Pt,resetBoard:on,refreshVersion:J,costSummaryAbortRef:X,costSummaryRequestVersion:Dt,setEntityPage:h,costsLoadedRef:Z,setCosts:M,setPeriodTransitionPending:Ne,periodTransitionVersionRef:Ct,setLoadingArea:B,navigate:ln,setHelpOpen:he,closeDocument:tt,documentDetail:nt,helpOpen:me,reconciliationResult:Re,setReconciliationResult:ze,refreshDialog:Fe,setTrace:ut,traceLink:ht,setTraceLoadingTaskId:ft,setTraceLink:dt,refreshFromDialog:cn,renderedOperations:d}}async function Pt(e){let t=await(await fetch(`/api/v2/health`,{cache:`no-store`,signal:e})).json();if(t?.kind!==`zaip-dashboard-sqlite-runtime`||typeof t.workspace!=`string`||typeof t.workspace_name!=`string`||![`initialized`,`missing`,`invalid`].includes(t.lifecycle_manifest_state))throw Error(`Identidade do Dashboard indisponível`);return t}function Ft(){let[e,t]=(0,m.useState)(null),[n,r]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{let e=!1,n,i;async function a(){i=new AbortController;let o=setTimeout(()=>i.abort(),4e3);try{let n=await Pt(i.signal);e||(t(n),r(!1))}catch{e||r(!0)}finally{clearTimeout(o),e||(n=setTimeout(a,5e3))}}return a(),()=>{e=!0,clearTimeout(n),i?.abort()}},[]),{status:e,unavailable:n}}function It({status:e,unavailable:t=!1}){let n=e?.lifecycle_manifest_state;return n===`initialized`&&e?.status===`ok`&&!t?null:(0,g.jsx)(`aside`,{className:`workspace-status`,"aria-label":`Saúde do Dashboard`,children:n===`missing`||n===`invalid`?(0,g.jsxs)(`div`,{className:`workspace-status__warning`,role:`alert`,children:[(0,g.jsx)(`strong`,{children:n===`missing`?`Lifecycle não inicializado`:`Manifesto do lifecycle inválido`}),(0,g.jsx)(`p`,{children:`Os dados deste workspace estão indisponíveis. Na pasta do projeto, execute:`}),(0,g.jsx)(`code`,{children:`node .agents/runtime/bin/zaip.mjs manifest rebuild --confirm-full-scan`})]}):e?.status===`degraded`||t?(0,g.jsx)(`p`,{className:`workspace-status__warning`,role:`status`,children:t?`Não foi possível consultar a saúde do Dashboard. Tentando novamente…`:`Dashboard degradado: a atualização dos dados ou da telemetria requer atenção.`}):(0,g.jsx)(`p`,{className:`workspace-status__warning`,role:`status`,children:`Identificando a saúde do Dashboard…`})})}function Lt(){let e=Nt(),t=Ft();return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(It,{...t}),t.status?.lifecycle_manifest_state===`initialized`?(0,g.jsx)(Se,{model:e}):null]})}var Rt=document.getElementById(`root`);if(!Rt)throw Error(`Elemento #root não encontrado`);(0,h.createRoot)(Rt).render((0,g.jsx)(m.StrictMode,{children:(0,g.jsx)(Lt,{})}));export{wt as n,Ft as t};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DashboardHelpDialog-DhlntQcR.js","assets/rolldown-runtime-Bh1tDfsg.js","assets/cost-monitor-uPnOBShc.js","assets/cost-monitor-C2AFYBu_.css","assets/dashboard-localization-DWXjEIgc.js","assets/DashboardHelpDialog-DRI_XwUf.css","assets/PricingSettingsDialog-BHoZT2an.js","assets/ProjectSettingsPage-IcncIZ9Y.js","assets/ProjectSettingsPage-CQMhvzvJ.css","assets/CostCalculationGuidePage-w6pjt4OM.js","assets/TraceabilityWorkspace-C6rORjpr.js","assets/traceability-IcefoTOv.js","assets/icons-vendor-Hc9fp_gs.js","assets/traceability-DFY7ZDlu.css","assets/TraceabilityWorkspace-DvvavDLY.css"])))=>i.map(i=>d[i]);
2
+ import{n as e}from"./rolldown-runtime-Bh1tDfsg.js";import{E as t,a as n,b as r,g as i,i as a,n as o,o as s,r as c,t as l,w as u}from"./cost-monitor-uPnOBShc.js";import{t as d}from"./react-vendor-C9ta_O10.js";import{n as f,t as p}from"./traceability-IcefoTOv.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var m=e(t(),1),h=d(),g=u();function _({locale:e}){let t=e===`pt-BR`?[`Definição`,`Planejamento`,`Pronto para Executar`,`Execução`,`Verificação`]:[`Definition`,`Planning`,`Ready to Execute`,`Execution`,`Verification`];return(0,g.jsxs)(`main`,{"aria-busy":`true`,"aria-live":`polite`,"aria-label":e===`pt-BR`?`Preparando dashboard`:`Preparing dashboard`,className:`app-skeleton`,role:`status`,children:[(0,g.jsxs)(`header`,{className:`app-skeleton-header`,children:[(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-short`}),(0,g.jsx)(`h1`,{children:`Dashboard ZAIP AIOS`})]}),(0,g.jsxs)(`div`,{className:`app-skeleton-actions`,children:[(0,g.jsx)(`span`,{}),(0,g.jsx)(`span`,{}),(0,g.jsx)(`span`,{})]})]}),(0,g.jsx)(`section`,{className:`app-skeleton-kpis`,"aria-hidden":`true`,children:Array.from({length:4},(e,t)=>`skeleton-kpi-${t}`).map(e=>(0,g.jsxs)(`article`,{children:[(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-short`}),(0,g.jsx)(`span`,{className:`app-skeleton-value`}),(0,g.jsx)(`span`,{className:`app-skeleton-line`})]},e))}),(0,g.jsxs)(`section`,{className:`app-skeleton-panels`,"aria-hidden":`true`,children:[(0,g.jsxs)(`article`,{children:[(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-medium`}),(0,g.jsx)(`div`,{className:`app-skeleton-chart`})]}),(0,g.jsxs)(`article`,{children:[(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-medium`}),(0,g.jsx)(`div`,{className:`app-skeleton-chart app-skeleton-chart-small`})]})]}),(0,g.jsx)(`section`,{className:`app-skeleton-board`,"aria-hidden":`true`,children:t.map((e,t)=>(0,g.jsxs)(`article`,{children:[(0,g.jsx)(`h2`,{children:e}),Array.from({length:t%2==0?2:1},(t,n)=>`${e}-${n}`).map(e=>(0,g.jsxs)(`div`,{className:`app-skeleton-card`,children:[(0,g.jsx)(`span`,{className:`app-skeleton-line`}),(0,g.jsx)(`span`,{className:`app-skeleton-line app-skeleton-line-medium`}),(0,g.jsx)(`span`,{className:`app-skeleton-pill`})]},e))]},e))})]})}function v(e,t){let n=t===`pt-BR`;return e===`costs`?n?{title:`Carregando Monitor de Custos…`,detail:`Isso costuma levar poucos segundos.`}:{title:`Loading Cost Monitor…`,detail:`This usually takes a few seconds.`}:e===`traceability`?n?{title:`Carregando Rastreabilidade…`,detail:`Estamos preparando as 6 etapas da task.`}:{title:`Loading Traceability…`,detail:`Preparing the task's 6 stages.`}:n?{title:`Atualizando dados do dashboard…`,detail:`Você pode continuar navegando.`}:{title:`Refreshing dashboard data…`,detail:`You can keep navigating.`}}function y({area:e,locale:t}){let n=v(e,t);return(0,g.jsxs)(`section`,{"aria-busy":`true`,"aria-live":`polite`,className:`app-loading-panel`,role:`status`,children:[(0,g.jsx)(`i`,{}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`strong`,{children:n.title}),(0,g.jsx)(`span`,{children:n.detail})]})]})}function b({area:e,locale:t}){let n=v(e,t);return(0,g.jsxs)(`section`,{"aria-live":`polite`,className:`app-refresh-status`,role:`status`,children:[(0,g.jsx)(`i`,{}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`strong`,{children:n.title}),(0,g.jsx)(`span`,{children:n.detail})]})]})}function x({locale:e,onRetry:t}){return(0,g.jsxs)(`section`,{"aria-live":`polite`,className:`app-loading-panel app-loading-panel-error`,role:`status`,children:[(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`strong`,{children:e===`pt-BR`?`Não foi possível carregar os custos`:`Couldn't load costs`}),(0,g.jsx)(`span`,{children:e===`pt-BR`?`A tela continua disponível. Tente novamente quando quiser.`:`The dashboard remains available. Try again whenever you want.`})]}),(0,g.jsx)(`button`,{onClick:t,type:`button`,children:e===`pt-BR`?`Tentar novamente`:`Try again`})]})}function S({costsLoaded:e,currency:t,snapshotCurrency:n}){return!e||n!==t}function C({aborted:e,currentCurrency:t,currentPeriod:n,currentRequestVersion:r,requestVersion:i,requestedCurrency:a,requestedPeriod:o}){return!e&&i===r&&a===t&&o.from===n.from&&o.to===n.to}function w(e,t){return e===t}function T(e,t,n,r){return w(e,t)&&n.from===r.from&&n.to===r.to}function E(e){return e instanceof DOMException&&e.name===`AbortError`}function D(e,t){return e===t}function O(e,t,n){return w(e,t)&&!n.aborted}function k(e,t){let n=e=>[...new Map(e.map(e=>[e.id,e])).values()];return{...e,prds:n([...e.prds,...t.flatMap(e=>e.prds)]),specs:n([...e.specs,...t.flatMap(e=>e.specs)]),tasks:n([...e.tasks,...t.flatMap(e=>e.tasks)]),changes:n([...e.changes,...t.flatMap(e=>e.changes)])}}function ee(){let e=(0,m.useRef)(null);return(0,m.useEffect)(()=>{e.current?.focus()},[]),(0,g.jsx)(`div`,{"aria-busy":`true`,"aria-live":`polite`,className:`period-transition-overlay`,onKeyDownCapture:e=>e.preventDefault(),ref:e,role:`status`,tabIndex:-1,children:(0,g.jsxs)(`div`,{className:`period-transition-overlay__content`,children:[(0,g.jsx)(`i`,{"aria-hidden":`true`,className:`period-transition-overlay__spinner`}),(0,g.jsx)(`span`,{className:`period-transition-overlay__label`,children:`Carregando...`})]})})}function te({pending:e,children:t}){return(0,g.jsx)(`div`,{"aria-hidden":e||void 0,inert:e,children:t})}var ne={"pt-BR":{action:`Tentar novamente`,guidance:`Abra a pasta dashboard dentro de .agents e dê dois cliques novamente no arquivo executável.`,title:`Não foi possível carregar o dashboard`},"en-US":{action:`Try again`,guidance:`Open the dashboard folder inside .agents, then double-click the executable file again.`,title:`Unable to load the dashboard`}};function re({children:e,error:t,globalLoadingPending:n,locale:r,onRefresh:i,operations:a,snapshotNotice:o,setupRoute:s}){if(s!==null)return s;if(t&&a===null){let e=ne[r];return(0,g.jsx)(`main`,{className:`app-loading-boundary`,"aria-labelledby":`dashboard-load-error-title`,children:(0,g.jsxs)(`section`,{className:`app-loading-boundary__card`,role:`alert`,children:[(0,g.jsx)(`div`,{"aria-hidden":`true`,className:`app-loading-boundary__status-icon`,children:(0,g.jsx)(`svg`,{"aria-hidden":`true`,focusable:`false`,viewBox:`0 0 24 24`,children:(0,g.jsx)(`path`,{d:`M12 8v4m0 4h.01M10.29 3.86 2.82 16.5A2 2 0 0 0 4.54 19.5h14.92a2 2 0 0 0 1.72-3L13.71 3.86a2 2 0 0 0-3.42 0Z`})})}),(0,g.jsxs)(`div`,{className:`app-loading-boundary__content`,children:[(0,g.jsx)(`p`,{className:`app-loading-boundary__eyebrow`,children:r===`pt-BR`?`Dashboard indisponível`:`Dashboard unavailable`}),(0,g.jsx)(`h1`,{id:`dashboard-load-error-title`,children:e.title}),(0,g.jsx)(`p`,{children:e.guidance})]}),(0,g.jsx)(`button`,{onClick:i,type:`button`,children:e.action})]})})}return a===null?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(_,{locale:r}),o,n?(0,g.jsx)(ee,{}):null,(0,g.jsx)(b,{area:`operations`,locale:r})]}):e}function A(e){let t=new Set(e.blocked.map(e=>e.id));return{reconciled:e.reconciled_ids.filter(e=>!t.has(e)).length,blocked:e.blocked.length,notReconciled:e.not_reconciled.length}}function j(e){let t=new Set(e.blocked.map(e=>e.id));return e.reconciled_ids.filter(e=>!t.has(e)).map(t=>{let n=e.outcomes?.find(e=>e.id===t);return{id:t,reason:n?.reason??null,status:n?.status??null}})}function M(e,t){return e===null?``:t===`pt-BR`?{completed:`Concluído`,delivered:`Entregue`,failed:`Falha técnica`,blocked:`Bloqueado`,cancelled:`Cancelado`}[e]??e:e}var ie={"Invocation is still running":`A invocação ainda está em execução. Foi preservada intencionalmente; isso não indica falha do comando.`,"Host terminated without delivery evidence":`O host encerrou sem evidências de entrega.`,"Host interrupted":`O host foi interrompido.`,"Child attempt stopped":`A tentativa do subagente foi encerrada.`,"Execution orphaned after the reconciliation grace period":`A execução ficou sem orquestrador ativo após o período de tolerância da reconciliação.`};function N(e,t){if(e===null)return t===`pt-BR`?`Motivo não informado.`:`No reason provided.`;if(t===`en-US`)return e;let n=e.match(/^Explicit orphan reconciliation found no active host invocation or terminal work outcome; repair is required before resuming \(Run (\S+)\)\.$/);if(n)return`A Run ${n[1]} ficou sem invocação ativa do host e sem evidência de um desfecho de entrega. A reconciliação registrou a interrupção; a entrega exige reparo e validação antes de retomar.`;let r=e.match(/^Execution (\S+) has no active orchestrator agent call after the reconciliation grace period\.?$/);return r?`A execução ${r[1]} não tem uma chamada de agente orquestrador ativa após o período de tolerância da reconciliação.`:ie[e.trim().replace(/\.$/,``)]??e}function P({result:e,locale:t,onDismiss:n}){let[r,i]=(0,m.useState)(!1),a=(0,m.useRef)(null),o=t===`pt-BR`,s=A(e),c=o?`Resultado da reconciliação manual`:`Manual reconciliation result`,l={reconciled:o?`Outros estados registrados`:`Other recorded outcomes`,blocked:o?`Desfechos bloqueados`:`Blocked outcomes`,notReconciled:o?`Não reconciliados`:`Not reconciled`},u=`${l.reconciled}: ${s.reconciled} · ${l.blocked}: ${s.blocked} · ${l.notReconciled}: ${s.notReconciled}`;return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsxs)(`section`,{className:`app-reconciliation-result`,"aria-label":c,children:[(0,g.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[(0,g.jsx)(`strong`,{children:c}),(0,g.jsx)(`p`,{children:u})]}),(0,g.jsxs)(`div`,{className:`app-reconciliation-actions`,children:[(0,g.jsx)(`button`,{ref:a,type:`button`,"aria-haspopup":`dialog`,onClick:()=>i(!0),children:o?`Veja mais`:`View details`}),(0,g.jsx)(`button`,{type:`button`,onClick:n,children:o?`Fechar`:`Dismiss`})]})]}),r?(0,g.jsx)(ae,{result:e,locale:t,title:c,summary:u,labels:l,onClose:()=>i(!1),restoreFocus:()=>a.current?.focus({preventScroll:!0})}):null]})}function ae({result:e,locale:t,title:n,summary:r,labels:i,onClose:a,restoreFocus:o}){let s=(0,m.useRef)(null),c=(0,m.useRef)(o),l=(0,m.useId)(),u=t===`pt-BR`;(0,m.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return e.showModal(),document.body.style.overflow=`hidden`,()=>{e.close(),document.body.style.overflow=t,c.current()}},[]);let d=[{label:i.reconciled,items:j(e),reasons:!0},{label:i.blocked,items:e.blocked,reasons:!0},{label:i.notReconciled,items:e.not_reconciled,reasons:!0}];return(0,g.jsxs)(`dialog`,{ref:s,className:`app-reconciliation-dialog`,"aria-labelledby":l,"aria-modal":`true`,onCancel:e=>{e.preventDefault(),a()},onKeyDown:e=>{if(e.key!==`Tab`)return;let t=Array.from(e.currentTarget.querySelectorAll(`button:not(:disabled), summary, [tabindex="0"]`)).filter(e=>e.getClientRects().length>0),n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r?.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n?.focus())},children:[(0,g.jsxs)(`header`,{children:[(0,g.jsx)(`h2`,{id:l,children:n}),(0,g.jsx)(`button`,{type:`button`,onClick:a,children:u?`Fechar detalhes`:`Close details`})]}),(0,g.jsxs)(`section`,{className:`app-reconciliation-details`,tabIndex:0,"aria-label":u?`Itens da reconciliação`:`Reconciliation items`,children:[(0,g.jsx)(`p`,{children:r}),(0,g.jsx)(`p`,{children:u?`A reconciliação registra o estado real de cada item. Desfechos bloqueados aparecem somente na categoria de bloqueios; um estado registrado não significa entrega concluída.`:`Reconciliation records each item's actual state. Blocked outcomes appear only in the blocked category; a recorded state does not imply completed delivery.`}),(0,g.jsx)(`p`,{children:u?`Última telemetria indica a coleta de tokens medidos. Registrar estados ou atualizar o snapshot sem novos tokens não altera esse horário.`:`Last telemetry means measured token collection. Recording states or refreshing the snapshot without new tokens does not change that time.`}),e.diagnostics?(0,g.jsxs)(`p`,{children:[u?`Reconciliação executada em`:`Reconciliation executed at`,` `,new Intl.DateTimeFormat(t,{dateStyle:`short`,timeStyle:`medium`}).format(new Date(e.diagnostics.completed_at)),` · Job: `,(0,g.jsx)(`code`,{children:e.diagnostics.job_id}),` · `,`Logs`,`: `,(0,g.jsx)(`code`,{children:e.diagnostics.log_directory})]}):null,(0,g.jsx)(`p`,{children:u?`Invocações ainda em execução são preservadas intencionalmente. Permanecer não reconciliado por esse motivo não indica falha do comando.`:`Invocations that are still running are intentionally preserved. Remaining unreconciled for this reason does not indicate a command failure.`}),d.map(e=>(0,g.jsxs)(`section`,{"aria-label":e.label,children:[(0,g.jsxs)(`h3`,{children:[e.label,` (`,e.items.length,`)`]}),e.items.length===0?(0,g.jsx)(`p`,{children:u?`Nenhum item nesta categoria.`:`No items in this category.`}):(0,g.jsx)(`ul`,{children:F(e.items).map(({item:n,key:r})=>(0,g.jsxs)(`li`,{children:[(0,g.jsx)(`code`,{children:n.id}),`status`in n&&typeof n.status==`string`?(0,g.jsx)(`p`,{children:M(n.status,t)}):null,e.reasons?(0,g.jsx)(`p`,{children:N(n.reason,t)}):null,e.reasons&&n.reason!==null&&N(n.reason,t)!==n.reason?(0,g.jsxs)(`details`,{children:[(0,g.jsx)(`summary`,{children:u?`Motivo original`:`Original reason`}),(0,g.jsx)(`p`,{children:n.reason})]}):null]},r))})]},e.label))]})]})}function F(e){let t=new Map;return e.map(e=>{let n=JSON.stringify([e.id,e.reason]),r=(t.get(n)??0)+1;return t.set(n,r),{item:e,key:`${n}:${r}`}})}var oe=`modulepreload`,se=function(e){return`/`+e},ce={},I=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=se(t,n),t=s(t),t in ce)return;ce[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:oe,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},le=(0,m.lazy)(async()=>({default:(await I(async()=>{let{DashboardHelpDialog:e}=await import(`./DashboardHelpDialog-DhlntQcR.js`);return{DashboardHelpDialog:e}},__vite__mapDeps([0,1,2,3,4,5]))).DashboardHelpDialog}));function ue({costLocale:e,documentDetail:t,helpOpen:n,loadingArea:i,operations:a,reconciliationResult:c,refreshDialog:l,showTrace:u,trace:d,traceLink:h,traceLoadingTaskId:_,closeDocument:v,onCloseHelp:y,onCloseTrace:x,onDismissReconciliation:S,onOpenDocument:C,onOpenTrace:w,onOpenTraceChange:T,onOpenTraceMacro:E,onRefreshCancel:D,onRefreshFromDialog:O,setTraceLink:k}){return(0,g.jsxs)(g.Fragment,{children:[u?null:_?(0,g.jsx)(p,{locale:e,taskId:_}):d?(0,g.jsx)(f,{locale:e,onClose:x,onOpenChange:T,onOpenPrd:e=>E(`PRD`,e),onOpenSpec:e=>E(`SPEC`,e),trace:d}):null,h?.kind===`change`?(0,g.jsx)(r,{details:{kind:`change`,row:h.row},locale:e,onClose:()=>k(null)}):null,h?.kind===`macro`?(0,g.jsx)(s,{label:h.label,locale:e,onClose:()=>k(null),onOpenDocument:C,onOpenTrace:e=>{k(null),w(e)},row:h.row,runs:a.runs,specs:a.specs,tasks:a.tasks}):null,t?(0,g.jsx)(o,{detail:t.detail,error:t.error,label:t.label,locale:e,loading:!t.detail&&!t.error,onClose:v,onRetry:()=>C(t.kind,t.preview.id),preview:t.preview}):null,n?(0,g.jsx)(m.Suspense,{fallback:null,children:(0,g.jsx)(le,{locale:e,onClose:y})}):null,l===`choose`?(0,g.jsx)(`div`,{className:`app-refresh-dialog-backdrop`,children:(0,g.jsxs)(`section`,{"aria-label":`Atualizar dashboard`,"aria-modal":`true`,className:`app-refresh-dialog`,role:`dialog`,children:[(0,g.jsx)(`h2`,{children:e===`pt-BR`?`Atualizar dashboard`:`Refresh dashboard`}),(0,g.jsx)(`p`,{children:e===`pt-BR`?`Escolha uma atualização rápida ou reconcilie os itens que ainda estão em aberto.`:`Choose a quick refresh or reconcile work items that are still open.`}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`button`,{onClick:()=>O(!1),type:`button`,children:e===`pt-BR`?`Apenas atualizar dados`:`Refresh data only`}),(0,g.jsx)(`button`,{onClick:()=>O(!0),type:`button`,children:e===`pt-BR`?`Reconciliar itens abertos`:`Reconcile open work`})]}),(0,g.jsx)(`button`,{className:`app-refresh-cancel`,onClick:D,type:`button`,children:e===`pt-BR`?`Cancelar`:`Cancel`})]})}):null,l===`refreshing`||l===`reconciling`?(0,g.jsxs)(`section`,{"aria-live":`polite`,className:`app-refresh-status`,role:`status`,children:[(0,g.jsx)(`i`,{}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`strong`,{children:l===`reconciling`?e===`pt-BR`?`Reconciliando itens em aberto…`:`Reconciling open work…`:e===`pt-BR`?`Atualizando dados…`:`Refreshing data…`}),(0,g.jsx)(`span`,{children:e===`pt-BR`?`Você pode continuar usando o dashboard.`:`You can keep using the dashboard.`})]})]}):null,c!==null&&l===null?(0,g.jsx)(P,{result:c,locale:e,onDismiss:S}):null,i!==null&&l===null?(0,g.jsx)(b,{area:i,locale:e}):null]})}var de=(0,m.lazy)(async()=>({default:(await I(async()=>{let{PricingSettingsPage:e}=await import(`./PricingSettingsDialog-BHoZT2an.js`);return{PricingSettingsPage:e}},__vite__mapDeps([6,1,2,3,4]))).PricingSettingsPage})),fe=(0,m.lazy)(async()=>({default:(await I(async()=>{let{ProjectSettingsPage:e}=await import(`./ProjectSettingsPage-IcncIZ9Y.js`);return{ProjectSettingsPage:e}},__vite__mapDeps([7,1,2,3,8]))).ProjectSettingsPage})),L=(0,m.lazy)(async()=>({default:(await I(async()=>{let{CostCalculationGuidePage:e}=await import(`./CostCalculationGuidePage-w6pjt4OM.js`);return{CostCalculationGuidePage:e}},__vite__mapDeps([9,1,2,3]))).CostCalculationGuidePage})),pe=`/setup-pricing`,me=`/setup-project`,he=`/cost-calculation-guide`;function ge(e){let{api:t,costLocale:n,fxRate:r,navigate:i,pathname:a,pricing:o,refresh:s,setFxRate:c,setPricing:l}=e;return a===`/setup-pricing`?o===null?(0,g.jsxs)(`main`,{className:`app-state`,children:[(0,g.jsx)(`p`,{children:n===`pt-BR`?`Configuração do projeto`:`Project settings`}),(0,g.jsx)(`h1`,{children:n===`pt-BR`?`Carregando catálogo de preços…`:`Loading pricing catalog…`}),(0,g.jsx)(`button`,{onClick:()=>i(`/`),type:`button`,children:n===`pt-BR`?`Voltar ao dashboard`:`Back to dashboard`})]}):(0,g.jsx)(m.Suspense,{fallback:null,children:(0,g.jsx)(de,{catalog:o,fxRate:r,locale:n,onClose:()=>i(`/`),onSave:async e=>{l(await t.savePricing(e)),await s()},onSaveFxRate:async e=>{c(await t.saveFxRate(e)),await s()}})}):a===`/cost-calculation-guide`&&o!==null?(0,g.jsx)(m.Suspense,{fallback:null,children:(0,g.jsx)(L,{catalog:o,fxRate:r,locale:n,onClose:()=>i(`/`)})}):a===`/setup-project`?(0,g.jsx)(m.Suspense,{fallback:null,children:(0,g.jsx)(fe,{api:t,locale:n,onClose:()=>i(`/`)})}):null}var _e=(0,m.lazy)(async()=>({default:(await I(async()=>{let{TraceabilityWorkspace:e}=await import(`./TraceabilityWorkspace-C6rORjpr.js`);return{TraceabilityWorkspace:e}},__vite__mapDeps([10,1,2,3,11,12,13,14]))).TraceabilityWorkspace}));function ve({costs:e,costLocale:t,currency:n,dashboardView:r,failedArea:i,lastUpdatedAt:a,loadCostDetail:o,loadCostReadModelPage:s,loadCostRunPage:c,loadCostGroupPage:u,loadingArea:d,onActiveDataChange:f,onCurrencyChange:p,onLoadingChange:h,onLocaleChange:_,onOpenTrace:v,onLoadMoreTraceTasks:b,onRefresh:S,onRetry:C,onSelectTraceTask:w,onOpenTraceChange:T,onOpenTraceMacro:E,operations:D,selectedTraceTaskId:O,trace:k,traceLoadingTaskId:ee,traceTasksHasMore:te,traceTasksLoading:ne,traceTasks:re}){return r===`cost-monitor`?e===null?()=>i===`costs`?(0,g.jsx)(x,{locale:t,onRetry:C}):(0,g.jsx)(y,{area:`costs`,locale:t}):r=>(0,g.jsx)(m.Suspense,{fallback:(0,g.jsx)(y,{area:`costs`,locale:t}),children:(0,g.jsx)(l,{currency:n,data:e,embedded:!0,globalFilters:r,lastUpdatedAt:a,locale:t,loading:d===`costs`,loadDetail:o,loadReadModelPage:s,loadRunPage:c,loadGroupPage:u,onActiveDataChange:f,onCurrencyChange:p,onLoadingChange:h,onLocaleChange:_,onOpenTrace:v,onRefresh:S,operations:D})}):r===`traceability`?()=>(0,g.jsx)(m.Suspense,{fallback:(0,g.jsx)(y,{area:`operations`,locale:t}),children:(0,g.jsx)(_e,{loadingTaskId:ee,locale:t,onOpenChange:T,onOpenPrd:e=>E(`PRD`,e),onOpenSpec:e=>E(`SPEC`,e),onLoadMoreTasks:b,onSelectTask:w,selectedTaskId:O,tasks:re.length>0?re:D.tasks,hasMoreTasks:te,isLoadingTasks:ne,trace:k})}):r===null?(0,g.jsx)(`span`,{"aria-hidden":`true`,hidden:!0}):void 0}function ye({currency:e,locale:t,onCurrencyChange:n,onHelpOpen:r,onNavigate:i,pricingSetupPath:a,projectSetupPath:o,costCalculationGuidePath:s}){return(0,g.jsxs)(`div`,{className:`dashboard-global-settings`,children:[(0,g.jsxs)(`label`,{children:[(0,g.jsx)(`span`,{children:t===`pt-BR`?`Moeda`:`Currency`}),(0,g.jsxs)(`select`,{"aria-label":t===`pt-BR`?`Moeda`:`Currency`,onChange:e=>n(e.target.value),value:e,children:[(0,g.jsx)(`option`,{value:`BRL`,children:`BRL · Real brasileiro`}),(0,g.jsx)(`option`,{value:`USD`,children:`USD · US Dollar`})]})]}),(0,g.jsx)(`button`,{className:`dashboard-help-open`,onClick:r,type:`button`,children:t===`pt-BR`?`Central de Ajuda`:`Open help and guides`}),(0,g.jsx)(`button`,{className:`dashboard-help-open`,onClick:()=>i(a),type:`button`,children:t===`pt-BR`?`Configurar preços e câmbio`:`Configure pricing and FX`}),(0,g.jsx)(`button`,{className:`dashboard-help-open`,onClick:()=>i(o),type:`button`,children:t===`pt-BR`?`Configurar projeto`:`Configure project`}),(0,g.jsx)(`button`,{className:`dashboard-help-open`,onClick:()=>i(s),type:`button`,children:t===`pt-BR`?`Guia de cálculo de custos`:`Cost calculation guide`})]})}var be={preset:`all`,range:a(`this-month`)};function R(e){return e.preset===`all`?{from:null,to:null}:{from:e.range.start,to:e.range.end}}function xe(e,t){let n=R(e),r=R(t);return n.from===r.from&&n.to===r.to}function Se({model:e}){let{operations:t,error:n,globalLoadingPending:r,costLocale:i,refresh:a,snapshotNotice:o,setupRoute:s,failedArea:l,retryLastLoad:u,costs:d,currency:f,dashboardView:p,lastUpdatedAt:m,loadCostDetail:h,loadCostReadModelPage:_,loadCostRunPage:v,loadCostGroupPage:y,loadingArea:b,setDisplayedCosts:x,setCurrency:S,setCostSurfaceLoading:C,changeDashboardLocale:w,loadMoreTraceTasks:T,openTrace:E,setRefreshDialog:D,setSelectedTraceTaskId:O,openTraceChange:k,openTraceMacro:ne,renderedOperations:A,selectedTraceTaskId:j,trace:M,traceLoadingTaskId:ie,traceTasksHasMore:N,traceTasksLoading:P,traceTasks:ae,capabilityNavigation:F,boardTotals:oe,boardKindTotals:se,boardExportSource:ce,detailExportSource:I,boardStates:le,operationsPeriod:de,entityPage:fe,dashboardIdentity:L,operationsLoading:ge,factualCostFact:_e,factualCostPeriods:be,setOperationsSurfaceLoading:R,operationsSurfaceLoading:Se,currentCostByRun:Ce,loadOperationsEntityPage:we,loadOperationsLifecyclePage:Te,loadOperationsDetails:Ee,entityPageKind:z,loadFilteredOperationsPage:De,loadFilteredBoard:Oe,loadWorkListFilters:ke,loadWorkListPage:Ae,workListFiltersRef:je,boardFiltersRef:Me,workListPage:Ne,overviewStatusPages:Pe,loadOverviewStatusPage:B,overviewClassificationPages:V,loadOverviewClassificationPage:H,openDocument:Fe,api:Ie,setError:U,operationsPeriodRef:Le,setOperationsPeriod:W,operationsDetailLoadedRef:Re,operationsDetailCancelRef:ze,operationsDetailAbortRef:Be,operationsPageAbortRef:Ve,resetWorkListPage:He,operationsPageRequestVersionRef:Ue,refreshVersion:We,costSummaryAbortRef:Ge,costSummaryRequestVersion:Ke,setEntityPage:qe,costsLoadedRef:Je,setCosts:Ye,setPeriodTransitionPending:Xe,periodTransitionVersionRef:Ze,setLoadingArea:G,navigate:K,setHelpOpen:Qe,closeDocument:$e,documentDetail:et,helpOpen:tt,reconciliationResult:nt,setReconciliationResult:rt,refreshDialog:it,setTrace:at,traceLink:ot,setTraceLink:st,refreshFromDialog:ct}=e,{loadMoreBoard:lt,overviewStatusPageKey:ut,overviewClassificationPageKey:dt,boardRequestVersionRef:ft,boardAbortControllersRef:pt,boardInFlightRef:mt,boardInitialPageRef:ht,boardLoadedRef:gt,setBoardTotals:_t,setBoardKindTotals:vt,setBoardStates:yt,setOverviewStatusPages:q,setOverviewClassificationPages:bt,setOperationsLoading:J}=e;return(0,g.jsxs)(re,{error:n,globalLoadingPending:r,locale:i,onRefresh:()=>void a(),operations:t,snapshotNotice:o,setupRoute:s,children:[(0,g.jsxs)(te,{pending:r,children:[n?(0,g.jsxs)(`div`,{"aria-live":`assertive`,className:`app-warning app-error`,role:`alert`,children:[(0,g.jsx)(`span`,{children:n}),l?(0,g.jsx)(`button`,{onClick:u,type:`button`,children:i===`pt-BR`?`Tentar novamente`:`Try again`}):null,(0,g.jsx)(`button`,{"aria-label":i===`pt-BR`?`Fechar erro`:`Dismiss error`,onClick:()=>U(null),type:`button`,children:`×`})]}):null,(0,g.jsx)(c,{alternateContent:ve({costs:d,costLocale:i,currency:f,dashboardView:p,failedArea:l,lastUpdatedAt:m,loadCostDetail:h,loadCostReadModelPage:_,loadCostRunPage:v,loadCostGroupPage:y,loadingArea:b,onActiveDataChange:x,onCurrencyChange:S,onLoadingChange:C,onLocaleChange:w,onLoadMoreTraceTasks:T,onOpenTrace:e=>void E(e),onRefresh:()=>D(`choose`),onRetry:u,onSelectTraceTask:e=>{O(e),E(e)},onOpenTraceChange:k,onOpenTraceMacro:ne,operations:A,selectedTraceTaskId:j,trace:M,traceLoadingTaskId:ie,traceTasksHasMore:N,traceTasksLoading:P,traceTasks:ae}),capabilityNavigation:F,boardTotals:oe,boardKindTotals:se,boardExportSource:ce,detailExportSource:I,boardStates:le,data:A,lastUpdatedAt:m,datePreset:de.preset,dateRange:de.range,entityPage:fe,dashboardTitle:L.title,repositoryName:L.repositoryName,loading:ge,locale:i,currency:f,factualCostFact:_e,costLoading:d===null&&l!==`costs`,factualCostPeriods:be,onLoadingChange:R,resolveRunCost:d===null?void 0:e=>Ce.get(e)??null,onLocaleChange:w,onDetailDataRequest:e=>{let t=e===`conversations`?`conversations`:e===`executions`?`executions`:e===`runs`?`runs`:null;t===null?e===`changes`||e===`decisions`?Te(e):Ee():we(t)},onLoadMacroMetrics:()=>{t?.summary.overview_metrics?.macro_metrics===void 0&&Ee()},onEntityPageChange:e=>{z===`changes`||z===`decisions`?Te(z,e):we(z,e)},onEntityFiltersChange:De,onBoardFiltersChange:Oe,onWorkListFiltersChange:ke,onWorkListPageChange:e=>void Ae(je.current,e),onBoardTypeChange:e=>Oe({...Me.current,kind:e===`all`?``:e}),onWorkListTypeChange:e=>void Ae({...je.current,kind:e===`all`?``:e}),onLoadMoreBoard:e=>void lt(e),workListPage:Ne,statusPage:(e,t)=>Pe[ut(e,t)],onLoadStatusPage:(e,t,n)=>void B(e,t,n),classificationPage:(e,t)=>V[dt(e,t)],onLoadClassificationPage:(e,t,n)=>void H(e,t,n),onOpenDocument:(e,t)=>void Fe(e,t),onOpenTask:E,onPriorityChange:async e=>{try{await Ie.saveWorkPriority(e)}catch(e){throw U(e instanceof Error?e.message:String(e)),e}},onDateChange:(e,t)=>{let n={preset:e,range:t};if(xe(Le.current,n)){W(n);return}Re.current=!1,ze.current?.(),ze.current=null,Be.current?.abort(),Be.current=null,Ve.current?.abort(),Ve.current=null,He(),++Ue.current,ft.current+=1;for(let e of pt.current.values())e.abort();pt.current.clear(),mt.current.clear(),ht.current.clear(),gt.current={},_t({}),vt({}),yt({}),q({}),bt({}),++We.current,Ge.current?.abort(),Ge.current=null,++Ke.current,qe({offset:0,total:null,loading:!1,error:null}),Je.current=!1,Ye(null),x(null),J(!0),Ze.current+=1,Xe(!0),G(`operations`),W(n)},onRefresh:()=>D(`choose`),settings:(0,g.jsx)(ye,{costCalculationGuidePath:he,currency:f,locale:i,onCurrencyChange:S,onHelpOpen:()=>Qe(!0),onNavigate:K,pricingSetupPath:pe,projectSetupPath:me})}),(0,g.jsx)(ue,{closeDocument:$e,costLocale:i,documentDetail:et,helpOpen:tt,loadingArea:b??(d===null&&l!==`costs`?`costs`:Se||Object.values(le).some(e=>e.loading)?`operations`:null),operations:A,reconciliationResult:nt,refreshDialog:it,showTrace:p===`traceability`,trace:M,traceLink:ot,traceLoadingTaskId:ie,onCloseHelp:()=>Qe(!1),onCloseTrace:()=>at(null),onDismissReconciliation:()=>rt(null),onOpenDocument:(e,t)=>void Fe(e,t),onOpenTrace:e=>void E(e),onOpenTraceChange:k,onOpenTraceMacro:ne,onRefreshCancel:()=>D(null),onRefreshFromDialog:e=>void ct(e),setTraceLink:e=>st(e)})]}),r?(0,g.jsx)(ee,{}):null]})}var Ce=(e,t)=>`${e}:${t}`,we=(e,t)=>`${e}:${t}`,Te=[`definition`,`planning`,`ready`,`executing`,`verifying`,`completed`,`blocked`,`cancelled`,`failed`],Ee=`/zaip-cost-monitor`,z=`zaip-dashboard-session-token`,De=`zaip-dashboard-locale`,Oe=`zaip-dashboard-currency`;function ke(){return window.localStorage.getItem(`zaip-dashboard-locale`)===`en-US`?`en-US`:`pt-BR`}function Ae(e){return e.replace(/\/+$/,``)===Ee?`cost-monitor`:null}function je(){let e=new URL(window.location.href),t=e.searchParams.get(`token`)??window.localStorage.getItem(`zaip-dashboard-session-token`)??window.sessionStorage.getItem(`zaip-dashboard-session-token`)??``;return t&&(window.localStorage.setItem(z,t),window.sessionStorage.setItem(z,t)),e.searchParams.has(`token`)&&(e.searchParams.delete(`token`),window.history.replaceState(null,``,`${e.pathname}${e.search}${e.hash}`)),t}var Me=class{token;constructor(e){this.token=e}ready(){return this.get(`/api/v2/ready`)}captureTelemetry(){return this.post(`/api/v2/capture-telemetry`)}dashboardIdentity(){return this.get(`/api/v2/dashboard-identity`)}operations(e,t=`detail`,n,r=!1){let a=`${i.operations}?scope=${t}${r?`&fresh=1`:``}`;return this.get(H(a,e),n)}sqliteViewPage(e,t,n={},r){let i=new URLSearchParams({view:e,offset:String(n.offset??0)});return n.limit!==void 0&&i.set(`limit`,String(n.limit)),n.query&&i.set(`query`,n.query),n.status&&i.set(`status`,n.status),n.risk&&i.set(`risk`,n.risk),n.provider&&i.set(`provider`,n.provider),n.model&&i.set(`model`,n.model),n.agent&&i.set(`agent`,n.agent),n.phase&&i.set(`phase`,n.phase),n.origin&&i.set(`origin`,n.origin),n.workType&&i.set(`workType`,n.workType),n.priority&&i.set(`priority`,n.priority),n.kind&&i.set(`kind`,n.kind),this.get(H(`/api/v2/sqlite-views?${i.toString()}`,t),r)}operationsBoard(e,t,n=0,r,a,o=4){let s=new URLSearchParams({scope:`board`,stage:t,offset:String(n),limit:String(o)});return r?.query&&s.set(`query`,r.query),r?.status&&s.set(`status`,r.status),r?.risk&&s.set(`risk`,r.risk),r?.origin&&s.set(`origin`,r.origin),r?.kind&&s.set(`kind`,r.kind),this.get(H(`${i.operations}?${s.toString()}`,e),a)}traceabilityTasks(e=0,t=10){let n=new URLSearchParams({scope:`traceability`,offset:String(e),limit:String(t)});return this.get(`${i.operations}?${n}`)}operationsClassification(e,t,n,r=0,a,o=50){let s=new URLSearchParams({scope:`classification`,kind:t,classification:n,offset:String(r),limit:String(o)});return this.get(H(`${i.operations}?${s.toString()}`,e),a)}operationsEntityPage(e,t,n=0,r,a){let o=Ne(t,n,r);return this.get(H(`${i.operations}/runs?${o}`,e),a)}operationsLifecyclePage(e,t,n=0,r,a){let o=Ne(t,n,r);return this.get(H(`${i.operations}/entities?${o}`,e),a)}operationsReadModelPage(e,t,n=0,r=50,a=``,o){let s=new URLSearchParams({kind:t,offset:String(n),limit:String(r)});return a&&s.set(`query`,a),this.get(H(`${i.operations}/read-models?${s.toString()}`,e),o)}costMonitor(e=`BRL`,t,n=`detail`,r,a,o=!1){let s=new URLSearchParams({currency:e,scope:n});o&&s.set(`fresh`,`1`);for(let[e,t]of Object.entries(a??{}))t&&s.set(e,t);return this.get(H(`${i.costMonitor}?${s.toString()}`,t),r)}costMonitorRuns(e=`BRL`,t,n,r=100,a,o){let s=new URLSearchParams({currency:e,scope:`runs`,offset:String(n),limit:String(r)});for(let[e,t]of Object.entries(o??{}))t&&s.set(e,t);return this.get(H(`${i.costMonitor}?${s.toString()}`,t),a)}snapshot(e=`BRL`,t){return this.get(H(`${i.snapshot}?currency=${e}`,t))}reconcileOpenWork(e=`BRL`,t){return this.post(H(`${i.reconcileOpenWork}?currency=${e}`,t),B)}refreshProjection(e=`BRL`,t){return this.post(H(`${i.refreshProjection}?currency=${e}`,t),B)}task(e){return this.get(i.task(e))}prd(e){return this.get(i.prd(e))}spec(e){return this.get(i.spec(e))}taskTrace(e,t){return this.get(i.taskTrace(e),t)}pricing(){return this.get(`/api/v2/pricing`)}async savePricing(e){let t=await fetch(`/api/v2/pricing`,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify(e)});if(!t.ok)throw Error(`Pricing update failed with HTTP ${t.status}`);return await t.json()}fxRate(){return this.get(`/api/v2/fx-rate`)}agentCatalog(){return this.get(i.agentCatalog)}agentPortraitUrl(e){return`/api/v2/agent-catalog-assets/${encodeURIComponent(e)}?token=${encodeURIComponent(this.token)}`}projectSettings(){return this.get(i.projectSettings)}projectOverview(){return this.get(`${i.projectSettings}/overview`)}async saveWorkPriority(e){let t=await fetch(i.workPriority,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify({item_ids:e})});if(!t.ok)throw Error(`Work priority update failed with HTTP ${t.status}`);return await t.json()}async saveProjectSettings(e){let t=await fetch(i.projectSettings,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.error??`Project settings update failed with HTTP ${t.status}`)}return await t.json()}async saveAgentCatalog(e){let t=e.map(({nickname_candidates:e,...t})=>t),n=await fetch(i.agentCatalog,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify({agents:t})});if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??`Agent catalog update failed with HTTP ${n.status}`)}return await n.json()}async saveFxRate(e){let t=await fetch(`/api/v2/fx-rate`,{method:`PUT`,headers:{"content-type":`application/json`,"x-zaip-session":this.token},body:JSON.stringify({rate:e})});if(!t.ok)throw Error(`FX update failed with HTTP ${t.status}`);return await t.json()}async get(e,t){let n=await V(e,{cache:`no-cache`,headers:{"x-zaip-session":this.token}},Pe,t);if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??`Dashboard API failed with HTTP ${n.status}`)}return await n.json()}async post(e,t=Pe){let n=await V(e,{method:`POST`,headers:{"x-zaip-session":this.token}},t);if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??`Dashboard API failed with HTTP ${n.status}`)}return await n.json()}};function Ne(e,t,n){let r=new URLSearchParams({kind:e,offset:String(t),limit:`100`});return n?.query&&r.set(`query`,n.query),n?.status&&r.set(`status`,n.status),n?.risk&&r.set(`risk`,n.risk),r.toString()}var Pe=6e4,B=18e4;async function V(e,t,n=Pe,r){let i=new AbortController,a=()=>i.abort();r?.addEventListener(`abort`,a,{once:!0}),r?.aborted&&i.abort();let o=window.setTimeout(()=>i.abort(),n);try{return await fetch(e,{...t,signal:i.signal})}catch(e){throw e instanceof DOMException&&e.name===`AbortError`?Error(`A leitura demorou mais de ${Math.ceil(n/1e3)} segundos. Tente novamente.`):e}finally{window.clearTimeout(o),r?.removeEventListener(`abort`,a)}}function H(e,t){if(t===void 0)return e;let n=new URL(e,`http://dashboard.local`);return t.from!==null&&n.searchParams.set(`from`,t.from),t.to!==null&&n.searchParams.set(`to`,t.to),`${n.pathname}${n.search}`}function Fe(e){return e.projection_refresh_completed}function Ie(e,t){return{reconciliation:e.reconciliation,dismissProgressDialog:!0,applySnapshotState:t,reloadQuickProjection:t&&Fe(e)}}var U={"pt-BR":{label:`Áreas do dashboard`,operations:`Operação`,operationsHint:`Trabalho em andamento e priorização`,costs:`Monitor de Custos`,costsHint:`Tempo, tokens e custo`,traceability:`Rastreabilidade`,traceabilityHint:`Ciclo completo em 6 etapas`},"en-US":{label:`Dashboard areas`,operations:`Operations`,operationsHint:`Lifecycle and work in progress`,costs:`Cost Monitor`,costsHint:`Time, tokens, and cost`,traceability:`Traceability`,traceabilityHint:`Complete 6-stage lifecycle`}};function Le({activeView:e,locale:t,onChange:n}){let r=U[t],i=e=>{n(e),window.requestAnimationFrame(()=>{document.querySelector(`.dashboard-global-controls`)?.scrollIntoView({behavior:`smooth`,block:`start`})})};return(0,g.jsxs)(`nav`,{"aria-label":r.label,className:`dashboard-capability-nav`,children:[(0,g.jsxs)(`button`,{"aria-current":e===`cost-monitor`?`page`:void 0,className:e===`cost-monitor`?`is-active`:void 0,onClick:()=>i(`cost-monitor`),type:`button`,children:[(0,g.jsx)(Re,{}),(0,g.jsxs)(`span`,{children:[(0,g.jsx)(`strong`,{children:r.costs}),(0,g.jsx)(`small`,{children:r.costsHint})]})]}),(0,g.jsxs)(`button`,{"aria-current":e===`operations`?`page`:void 0,className:e===`operations`?`is-active`:void 0,onClick:()=>i(`operations`),type:`button`,children:[(0,g.jsx)(W,{}),(0,g.jsxs)(`span`,{children:[(0,g.jsx)(`strong`,{children:r.operations}),(0,g.jsx)(`small`,{children:r.operationsHint})]})]}),(0,g.jsxs)(`button`,{"aria-current":e===`traceability`?`page`:void 0,className:e===`traceability`?`is-active`:void 0,onClick:()=>i(`traceability`),type:`button`,children:[(0,g.jsx)(ze,{}),(0,g.jsxs)(`span`,{children:[(0,g.jsx)(`strong`,{children:r.traceability}),(0,g.jsx)(`small`,{children:r.traceabilityHint})]})]})]})}function W(){return(0,g.jsxs)(`svg`,{"aria-hidden":`true`,className:`lucide lucide-square-kanban`,viewBox:`0 0 24 24`,children:[(0,g.jsx)(`rect`,{height:`18`,rx:`2`,width:`18`,x:`3`,y:`3`}),(0,g.jsx)(`path`,{d:`M8 7v7`}),(0,g.jsx)(`path`,{d:`M12 7v4`}),(0,g.jsx)(`path`,{d:`M16 7v9`})]})}function Re(){return(0,g.jsxs)(`svg`,{"aria-hidden":`true`,className:`lucide lucide-circle-dollar-sign`,viewBox:`0 0 24 24`,children:[(0,g.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,g.jsx)(`path`,{d:`M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8`}),(0,g.jsx)(`path`,{d:`M12 18V6`})]})}function ze(){return(0,g.jsxs)(`svg`,{"aria-hidden":`true`,className:`lucide lucide-route`,viewBox:`0 0 24 24`,children:[(0,g.jsx)(`circle`,{cx:`6`,cy:`19`,r:`3`}),(0,g.jsx)(`path`,{d:`M9 19h6.5a3.5 3.5 0 0 0 0-7h-7a3.5 3.5 0 0 1 0-7H18`}),(0,g.jsx)(`circle`,{cx:`18`,cy:`5`,r:`3`})]})}function Be(e){m.useEffect(()=>{if(!e)return;let t=new EventSource(`/api/v2/browser-lease?token=${encodeURIComponent(e)}`);return()=>t.close()},[e])}function Ve(e,t,n){return(0,g.jsx)(`div`,{className:`dashboard-capability-shell dashboard-capability-shell--${e??`initial`}`,children:(0,g.jsx)(Le,{activeView:e,locale:t,onChange:n})})}function He(e){return t=>{window.history.pushState(null,``,t),e(t),window.scrollTo({left:0,top:0})}}function Ue(e,t,n){return new Map((t??e)?.runs.map(e=>[e.run_id,n===`USD`?e.estimated_usd:e.estimated_brl])??[])}function We(e,t,n){let r=t??e;if(r?.currency!==n)return{fact:{state:`unavailable`,knownSum:null,coverage:null},periods:void 0};let i=r.overview.coverage[n===`USD`?`usd`:`brl`],a=n===`USD`?r.overview.estimated_usd:r.overview.estimated_brl,o={known:i,total:r.overview.run_count};return{fact:a===null?{state:`unavailable`,knownSum:null,coverage:o}:i<r.overview.run_count?{state:`partial`,knownSum:a,coverage:o}:{state:`complete`,knownSum:a,coverage:o},periods:{day:r.groups.daily,month:r.groups.monthly,year:r.groups.annual}}}var Ge={title:`Dashboard ZAIP AIOS`,repositoryName:``};function Ke(e,t){let n=typeof t.title==`string`?t.title.trim():``,r=typeof t.repository_name==`string`?t.repository_name.trim():``;return{title:n||e.title,repositoryName:r}}function qe(e,t,n,r,i,a,o,s){s(null),e===`costs`?r():e===`traceability`&&t?i(t):e===`operations`&&n!==null?a():o()}function Je(e,t,n,r,i,a,o,s,c){return ge({api:e,costLocale:t,fxRate:n,navigate:r,pathname:i,pricing:a,refresh:async()=>{await o()},setFxRate:s,setPricing:c})}function Ye(e){return async t=>{if(e.setDashboardView(t),window.scrollTo({left:0,top:0}),t===`cost-monitor`?S({costsLoaded:e.costsLoadedRef.current,currency:e.currency,snapshotCurrency:e.costs?.currency})&&(e.costSummaryAbortRef.current===null||e.costSummaryAbortRef.current.signal.aborted)&&e.loadCostSummary():e.costSummaryAbortRef.current?.abort(),t===`traceability`){let t=e.traceTasks;if(t.length===0){let n=e.boardRequestVersionRef.current;if(t=await e.loadMoreTraceTasks(!1,!0),n!==e.boardRequestVersionRef.current)return;e.setTraceTasks(t)}let n=t.toSorted((e,t)=>Date.parse(t.finished_at??t.updated_at)-Date.parse(e.finished_at??e.updated_at)),r=n.find(e=>e.status===`completed`)??n[0];r&&(e.setSelectedTraceTaskId(r.id),e.openTrace(r.id));return}e.setTrace(null),e.setTraceLoadingTaskId(null)}}function Xe(e,t=new Date){return e.preset===`custom`?e:e.preset===`all`?{...e,range:a(`this-month`,t)}:{...e,range:a(e.preset,t)}}function Ze(e=new Date){let t=n(e.toISOString(),`day`);if(t===null)throw RangeError(`Invalid Sao Paulo day anchor`);let r=e.getTime(),i=r+1800*60*1e3;for(;n(new Date(i).toISOString(),`day`)===t;)i+=360*60*1e3;for(;i-r>1;){let e=Math.floor((r+i)/2);n(new Date(e).toISOString(),`day`)===t?r=e:i=e}return Math.max(1,i-e.getTime()+25)}function G(e){return typeof e==`number`?e:null}function K(e){return typeof e==`number`?{known_sum:e,unknown:0,complete:!0,coverage_ratio:1}:{known_sum:0,unknown:1,complete:!1,coverage_ratio:0}}function Qe(e){return Object.hasOwn(e,`total_duration`)?G(e.total_duration):G(e.cost_monitor_total_duration)}function $e(e,t,n){let{filters:r,query:i}=e;return{offset:t,limit:n,...i===void 0||i===``?{}:{query:i},...r.provider?{provider:r.provider}:{},...r.model?{model:r.model}:{},...r.agent?{agent:r.agent}:{},...r.phase?{phase:r.phase}:{},...r.status?{status:r.status}:{},...r.origin?{origin:r.origin}:{},...r.workType?{workType:r.workType}:{},...r.priority?{priority:r.priority}:{},...r.risk?{risk:r.risk}:{}}}function et(e){let t=Qe(e),n=Number(e.duration_unknown??+(t===null)),r=t??G(e.duration_known)??0;return{key:String(e.key??e.period_key??`total`),label:String(e.label??e.key??e.period_key??``),latest_started_at:typeof e.latest_started_at==`string`?e.latest_started_at:``,persona:typeof e.persona==`string`?e.persona:null,job:typeof e.job==`string`?e.job:null,run_count:Number(e.total_run_count??e.invocation_count??0),task_count:G(e.task_count),conversation_count:Number(e.conversation_count??0),prd_count:G(e.prd_count),spec_count:G(e.spec_count),evidence_count:G(e.evidence_count),test_count:G(e.validation_count),event_count:Number(e.source_event_count??0),total_tokens:G(e.total_tokens),estimated_usd:G(e.total_cost_usd),estimated_brl:G(e.total_cost_brl),duration_ms:t,duration:{known_sum:r,unknown:n,complete:n===0,coverage_ratio:+(n===0)},coverage:{events:0,tokens:0,usd:0,brl:0}}}async function tt(e,t){let{from:n,limit:r,offset:i,signal:a,to:o,view:s}=t,c=n===void 0||o===void 0?void 0:{from:n,to:o};if(s===`daily`){let n=await e.sqliteViewPage(`cost_monitor_daily`,c,$e(t,i,r),a);return{offset:n.offset,limit:n.limit,total_count:n.total_count,has_more:n.has_more,rows:n.rows.map(et),...n.period_averages===void 0?{}:{period_averages:n.period_averages},...n.totals===void 0?{}:{totals:et(n.totals)}}}let l={monthly:`cost_monitor_monthly`,annual:`cost_monitor_annual`,agents:`cost_monitor_zaip_agents`,models:`cost_monitor_models`,providers:`cost_monitor_providers`}[s],u=await e.sqliteViewPage(l,c,$e(t,i,r),a);return{offset:u.offset,limit:u.limit,total_count:u.total_count,has_more:u.has_more,rows:u.rows.map(et),...u.period_averages===void 0?{}:{period_averages:u.period_averages},...u.totals===void 0?{}:{totals:et(u.totals)}}}async function nt(e,t){let{filters:n,from:r,limit:i=10,offset:a,signal:o,to:s}=t,c=await e.sqliteViewPage(`cost_monitor_agent_invocations`,r===void 0||s===void 0?void 0:{from:r,to:s},{offset:a,limit:i,...n?.query?{query:n.query}:{},...n?.provider?{provider:n.provider}:{},...n?.model?{model:n.model}:{},...n?.agent?{agent:n.agent}:{},...n?.phase?{phase:n.phase}:{},...n?.status?{status:n.status}:{},...n?.priority?{priority:n.priority}:{},...n?.risk?{risk:n.risk}:{},...n?.origin?{origin:n.origin}:{},...n?.workType?{workType:n.workType}:{}},o);return{page_only:!0,runs:c.rows.map(rt),run_page:{offset:c.offset,limit:c.limit,total:c.total_count,has_more:c.has_more}}}function rt(e){let t=(e,t)=>typeof e==`string`?e:t,n=e=>typeof e==`number`?e:null,r=t(e.agent_invocation_id,`unavailable`),i=typeof e.task_id==`string`?e.task_id:null,a=typeof e.spec_id==`string`?e.spec_id:null,o=typeof e.prd_id==`string`?e.prd_id:null,s=t(e.phase,`execution`),c=e.duration_provenance===`observed`||e.duration_provenance===`reconciled`||e.duration_provenance===`estimated`||e.duration_provenance===`legacy_inferred`?e.duration_provenance:`unavailable`,l=Object.hasOwn(e,`calculated_cost_usd`)?n(e.calculated_cost_usd):n(e.cost_usd),u=n(e.current_fx_rate)??n(e.fx_rate),d=n(e.recorded_cost_usd)??n(e.recorded_usd),f=Object.hasOwn(e,`recorded_fx_rate`)?n(e.recorded_fx_rate):n(e.fx_rate),p=n(e.recorded_brl)??(!Object.hasOwn(e,`recorded_brl`)&&d!==null?n(e.cost_brl):null),m=l!==null&&u!==null?Math.round(l*u*1e6)/1e6:null;return{run_id:r,execution_id:typeof e.execution_id==`string`?e.execution_id:null,conversation_id:t(e.run_id,r),task_id:i,task_title:t(e.task_title,i??`Tarefa avulsa`),task_status:t(e.task_status,`unavailable`),priority:t(e.priority,`unavailable`),risk:t(e.risk,`unavailable`),spec_id:a,prd_id:o,change_id:typeof e.change_id==`string`?e.change_id:null,parent_run_id:typeof e.parent_agent_invocation_id==`string`?e.parent_agent_invocation_id:null,run_role:e.invocation_kind===`subagent`?`subagent`:`orchestrator`,run_kind:e.run_kind===`subrun`?`subrun`:`run`,run_purpose:`execution`,requires_finalizer:!1,client:t(e.client,`unavailable`),agent:t(e.zaip_agent,`unavailable`),agent_name:t(e.zaip_agent,`unavailable`),provider:typeof e.provider==`string`?e.provider:null,model:t(e.model,`unavailable`),requested_model:t(e.requested_model,`unavailable`),reasoning_effort:typeof e.reasoning_effort==`string`?e.reasoning_effort:null,effective_reasoning_effort:typeof e.effective_reasoning_effort==`string`?e.effective_reasoning_effort:null,service_tier:typeof e.service_tier==`string`?e.service_tier:null,call_count:n(e.llm_call_count),status:t(e.status,`completed`),phase:s,origin:o===null?a===null?i===null?`conversation`:`task`:`spec`:`prd`,work_type:e.work_type===`rework`?`rework`:`new`,started_at:t(e.occurred_at,``),finished_at:typeof e.finished_at==`string`?e.finished_at:null,duration_ms:n(e.duration_ms),duration_provenance:c,estimation_basis:typeof e.estimation_basis==`string`?e.estimation_basis:null,source_started_at:typeof e.source_started_at==`string`?e.source_started_at:null,source_finished_at:typeof e.source_finished_at==`string`?e.source_finished_at:null,capture_lag_ms:n(e.capture_lag_ms),event_count:n(e.source_event_count),input_tokens:n(e.input_tokens),cached_input_tokens:n(e.cached_input_tokens),output_tokens:n(e.output_tokens),reasoning_tokens:n(e.reasoning_tokens),total_tokens:n(e.total_tokens),uncached_input_tokens:n(e.uncached_input_tokens),visible_output_tokens:n(e.visible_output_tokens),input_rate_usd_per_million:n(e.input_rate_usd_per_million),cached_input_rate_usd_per_million:n(e.cached_input_rate_usd_per_million),output_rate_usd_per_million:n(e.output_rate_usd_per_million),reasoning_rate_usd_per_million:n(e.reasoning_rate_usd_per_million),context_input_multiplier:n(e.context_input_multiplier),context_output_multiplier:n(e.context_output_multiplier),speed_cost_multiplier:n(e.speed_cost_multiplier),standard_cost_usd:n(e.standard_cost_usd),speed_uplift_usd:n(e.speed_uplift_usd),input_cost_usd:n(e.input_cost_usd),cached_input_cost_usd:n(e.cached_input_cost_usd),output_cost_usd:n(e.output_cost_usd),reasoning_cost_usd:n(e.reasoning_cost_usd),fx_rate:u,estimated_usd:l,estimated_brl:m,recorded_usd:d,recorded_brl:p,recorded_fx_rate:f,coverage:{events:0,tokens:0,usd:0,brl:0},artifact_path:`.agents/records/runs/${r}`}}function it(e,t){let n=t.totals,r=e=>K(n?.[e]);return{data_source:`lifecycle_daily_read_models`,snapshot_id:null,source_latest_at:null,kind:e,offset:t.offset,limit:t.limit,total:t.total_count,has_more:t.has_more,next_cursor:null,subtotal:{entity_count:typeof n?.entity_count==`number`?n.entity_count:t.total_count,run_count:r(`invocation_count`),metrics:{duration:r(`total_duration`),total_tokens:r(`total_tokens`),cost_brl:r(`total_cost_brl`),cost_usd:r(`total_cost_usd`)}},rows:t.rows.map(t=>({id:String(t.task_id??t.spec_id??t.prd_id??t.execution_id??t.conversation_id??t.id??`unavailable`),title:String(t.title??t.task_id??t.spec_id??t.prd_id??t.execution_id??t.conversation_id??`Unavailable`),kind:e===`tasks`?`task`:e===`specs`?`spec`:e===`prds`?`prd`:e===`executions`?`execution`:`conversation`,status:typeof t.status==`string`?t.status:null,risk:typeof t.risk==`string`?t.risk:null,occurred_at:typeof t.occurred_at==`string`?t.occurred_at:typeof t.started_at==`string`?t.started_at:typeof t.last_day==`string`?`${t.last_day}T12:00:00.000Z`:``,parent_id:null,run_count:Number(t.invocation_count??0),cost_currency:`BRL`,metrics:{duration:K(t.total_duration),total_tokens:K(t.total_tokens),cost:K(t.total_cost_brl)}}))}}function at(e){return{loadCostDetail:(0,m.useCallback)(async()=>{throw Error(`SQLite Cost Monitor loads the selected paginated view; full detail is disabled.`)},[]),loadCostReadModelPage:(0,m.useCallback)(async({filters:t,from:n,kind:r,limit:i,offset:a,query:o,signal:s,to:c})=>{let l={tasks:`cost_monitor_tasks`,specs:`cost_monitor_specs`,prds:`cost_monitor_prds`,executions:`cost_monitor_executions`,conversations:`cost_monitor_conversations`}[r];return it(r,await e.sqliteViewPage(l,n===void 0||c===void 0?void 0:{from:n,to:c},{offset:a,limit:i,...t.query||o?{query:t.query||o}:{},...t.provider?{provider:t.provider}:{},...t.model?{model:t.model}:{},...t.agent?{agent:t.agent}:{},...t.phase?{phase:t.phase}:{},...t.status?{status:t.status}:{},...t.origin?{origin:t.origin}:{},...t.workType?{workType:t.workType}:{},...t.priority?{priority:t.priority}:{},...t.risk?{risk:t.risk}:{}},s))},[e]),loadCostRunPage:(0,m.useCallback)(t=>nt(e,t),[e]),loadCostGroupPage:(0,m.useCallback)(t=>tt(e,t),[e])}}function ot(e,t){return!1}function st(e,t=window,n=0){let r=!1,i=!1,a=new AbortController,o=t.setTimeout(()=>{r||i||(i=!0,e(a.signal))},n);return()=>{r||(r=!0,a.abort(),t.clearTimeout(o))}}var ct=2e3,lt=5e3,ut=1e4,dt=3e4,ft=`A atualização do snapshot não foi concluída. Os dados exibidos podem estar desatualizados.`;function pt(e,t){return e&&t<90}function mt(e,t){return e===`visible`?lt:t>0?dt:ut}function ht(e,t){return e!==null&&typeof t==`string`&&t.length>0&&e!==t}function gt(e,t){return(e===`current`||e===`updating`)&&typeof t==`string`&&t.length>0}function _t({observedRevision:e,pendingRevision:t,requestedRevision:n,succeeded:r}){return r?{observedRevision:n,pendingRevision:t===n?null:t}:{observedRevision:e,pendingRevision:t}}function vt({inFlight:e,lastRefreshAt:t,now:n,visibilityState:r}){return r===`visible`&&!e&&n-t>=5e3}function yt({api:e,costLocale:t,currency:n,dashboardView:r,loadOperationsDetails:i,operations:a,operationsDetailAbortRef:o,operationsDetailCancelRef:s,operationsPageAbortRef:c,pathname:l,pricing:u,refresh:d,refreshVersion:f,snapshotUpdating:p,setSnapshotUpdating:h,setError:g,setFxRate:_,setPathname:v,setPricing:y}){let b=(0,m.useRef)(!1),x=(0,m.useRef)(0),S=(0,m.useRef)(null),C=(0,m.useRef)(!1),w=(0,m.useRef)(null);(0,m.useEffect)(()=>(d(),()=>{s.current?.(),s.current=null,o.current?.abort(),o.current=null,c.current?.abort(),c.current=null,++f.current}),[o,s,c,d,f]),(0,m.useEffect)(()=>{let e=()=>{let e=Date.now();vt({inFlight:b.current,lastRefreshAt:x.current,now:e,visibilityState:document.visibilityState})&&(x.current=e,b.current=!0,d(!1,!1,!0).finally(()=>{b.current=!1}))};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[d]),(0,m.useEffect)(()=>{if(!p)return;let t=!1,n=0,r=null,i=async()=>{if(!(t||!pt(!0,n))){n+=1;try{let n=await e.ready();if(t)return;if(n.snapshot_state===`current`){h(!1),await d(!1,!1,!1,!0);return}}catch{}if(!t){if(pt(!0,n)){r=window.setTimeout(()=>void i(),ct);return}h(!1),g(ft)}}};return i(),()=>{t=!0,r!==null&&window.clearTimeout(r)}},[e,d,g,h,p]),(0,m.useEffect)(()=>{let t=!1,n=0,r=null,i=()=>{if(t||C.current)return;let e=w.current;e!==null&&(C.current=!0,d(!1,!1,!1,!0).then(t=>{t&&h(!1);let n=_t({observedRevision:S.current,pendingRevision:w.current,requestedRevision:e,succeeded:t});S.current=n.observedRevision,w.current=n.pendingRevision}).finally(()=>{C.current=!1,w.current!==e&&i()}))},a=async()=>{try{let r=await e.ready();if(t)return;n=0;let a=S.current;gt(r.snapshot_state,r.snapshot_revision)&&(a===null&&(S.current=r.snapshot_revision),ht(a,r.snapshot_revision)&&(w.current=r.snapshot_revision,i()))}catch{n+=1}t||(r=window.setTimeout(()=>void a(),mt(document.visibilityState,n)))};return a(),()=>{t=!0,r!==null&&window.clearTimeout(r)}},[e,d,h]),(0,m.useEffect)(()=>{if(!ot(r,a?.summary.overview_metrics?.partial===!0))return;let e=st(async e=>{await i(e)});return s.current=e,()=>{s.current===e&&(s.current=null),e()}},[r,i,a?.summary.overview_metrics?.partial,s]),(0,m.useEffect)(()=>window.localStorage.setItem(De,t),[t]),(0,m.useEffect)(()=>window.localStorage.setItem(Oe,n),[n]),(0,m.useEffect)(()=>{[`/`,`/setup-pricing`,`/setup-project`].includes(window.location.pathname)||(window.history.replaceState(null,``,`/${window.location.search}${window.location.hash}`),v(`/`))},[v]),(0,m.useEffect)(()=>{let e=()=>v(window.location.pathname);return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[v]),(0,m.useEffect)(()=>{l!==`/setup-pricing`||u!==null||Promise.all([e.pricing(),e.fxRate()]).then(([e,t])=>{y(e),_(t)}).catch(e=>g(String(e)))},[e,l,u,g,_,y])}var q={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 bt(e,t,n){let r=e=>e===`intake`||e===`orchestration`||e===`execution`||e===`review`||e===`audit`||e===`finalization`?e:`execution`,i=n.rows.map(e=>({id:e.id,artifact_path:`.agents/records/runs/${e.id}`,status:e.status===`running`||e.status===`failed`||e.status===`cancelled`?e.status:`completed`,phase:e.phase??`execution`,entrypoint:e.conversation_id===null?`task`:`conversation`,work_type:`new`,run_role:e.run_kind===`subrun`?`subagent`:`orchestrator`,run_kind:e.run_kind??`run`,run_purpose:r(e.run_purpose),requires_finalizer:!1,parent_run_id:e.parent_run_id,client:e.client??`unknown`,agent:e.agent??`unknown`,agent_name:e.agent??`unknown`,agent_persona:e.agent_persona??null,agent_job:e.agent_job??null,provider:e.provider??null,model:e.model??`unknown`,reasoning_effort:e.reasoning_effort??null,effective_model:e.model??null,effective_reasoning_effort:e.reasoning_effort??null,effective_config_mixed:e.pricing_mixed??!1,service_tier:e.service_tier??null,call_count:e.llm_call_count??null,terminal_call_count:null,failed_call_count:null,cancelled_call_count:null,conversation_id:e.conversation_id??e.id,execution_id:e.execution_id,task_id:e.task_id,spec_id:null,prd_id:null,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===void 0?e.duration_ms:e.source_duration_ms,duration_provenance:e.duration_provenance===`observed`||e.duration_provenance===`reconciled`||e.duration_provenance===`legacy_inferred`||e.duration_provenance===`estimated`?e.duration_provenance:`unavailable`,llm_call_count:e.llm_call_count??null,input_tokens:e.input_tokens??null,cached_input_tokens:e.cached_input_tokens??null,uncached_input_tokens:e.uncached_input_tokens??null,output_tokens:e.output_tokens??null,reasoning_tokens:e.reasoning_tokens??null,visible_output_tokens:e.visible_output_tokens??null,input_rate_usd_per_million:e.input_rate_usd_per_million??null,cached_input_rate_usd_per_million:e.cached_input_rate_usd_per_million??null,output_rate_usd_per_million:e.output_rate_usd_per_million??null,reasoning_rate_usd_per_million:e.reasoning_rate_usd_per_million??null,context_input_multiplier:e.context_input_multiplier??null,context_output_multiplier:e.context_output_multiplier??null,speed_cost_multiplier:e.speed_cost_multiplier??null,pricing_scenario:e.pricing_scenario??null,standard_cost_usd:e.standard_cost_usd??null,speed_uplift_usd:e.speed_uplift_usd??null,input_cost_usd:e.input_cost_usd??null,cached_input_cost_usd:e.cached_input_cost_usd??null,output_cost_usd:e.output_cost_usd??null,reasoning_cost_usd:e.reasoning_cost_usd??null,calculated_cost_usd:e.calculated_cost_usd??null,recorded_cost_usd:e.recorded_cost_usd??null,cost_variance_usd:e.cost_variance_usd??null,cost_usd:e.cost_usd??null,cost_brl:e.currency===`BRL`?e.cost:null,fx_rate:e.fx_rate??null,pricing_segment_count:e.pricing_segment_count??null,pricing_mixed:e.pricing_mixed??!1,pricing_model:e.pricing_model??null,pricing_source:e.pricing_source??null,...e.lifecycle_elapsed_ms===void 0?{}:{lifecycle_elapsed_ms:e.lifecycle_elapsed_ms},usage:{conversation:q,planning:q,execution:{...q,events:e.llm_call_count??0,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:e.cost_usd??null,brl:e.currency===`BRL`?e.cost:null}},total:{...q,events:e.llm_call_count??0,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:e.cost_usd??null,brl:e.currency===`BRL`?e.cost:null}},new_work:q,rework:q}}));return{...e,runs:i,executions:t===`executions`||t===`conversations`?n.rows.map((e,n)=>{let r=i[n];if(r===void 0)throw Error(`Operations entity page must have a projected run for every row.`);let a=r.execution_id??r.conversation_id,o=e.status??`unavailable`;return{id:a,kind:t===`conversations`?`interaction`:`delivery`,created_at:r.started_at,status:o,work_status:o,origin:t===`conversations`?{type:`interaction`,conversation_id:r.conversation_id}:{type:`task`,task_id:r.task_id??`unavailable`},dag:{nodes:[],topological_order:[]},result:null,artifact_path:`.agents/records/executions/${a}`,agent_call_count:0,orchestrator_run_count:0,subagent_run_count:0,finalizer_run_count:0,finalized_task_count:0,llm_call_count:0,llm_call_count_complete:!1,task_count:0,spec_count:0,prd_count:0,duration_ms:r.source_duration_ms??null,...e.lifecycle_elapsed_ms===void 0?{}:{lifecycle_elapsed_ms:e.lifecycle_elapsed_ms},total_tokens:r.usage.total.tokens.total,cost_brl:r.usage.total.cost.brl}}):e.executions}}function J(e){if(typeof e!=`string`)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function xt({api:e,entityFiltersRef:t,operationsPageAbortRef:n,operationsPageRequestVersionRef:r,operationsPeriod:i,operationsPeriodRef:a,refreshVersion:o,setEntityPage:s,setEntityPageKind:c,setOperations:l}){return{loadOperationsEntityPage:(0,m.useCallback)(async(u,d=0,f=t.current)=>{n.current?.abort();let p=new AbortController;n.current=p;let m=++r.current,h=o.current,g=R(i),_=()=>O(m,r.current,p.signal)&&T(h,o.current,g,R(a.current));c(u),s({offset:d,total:null,loading:!0,error:null});try{let t={runs:`operations_agent_invocations`,executions:`operations_executions`,conversations:`operations_conversations`}[u],n=await e.sqliteViewPage(t,g,{offset:d,limit:100,...f.query?{query:f.query}:{},...f.status?{status:f.status}:{},...f.risk?{risk:f.risk}:{}},p.signal),r={kind:u,offset:n.offset,limit:n.limit,total:n.total_count,aggregation:`canonical_entity`,rows:n.rows.map(e=>({id:String(e.agent_invocation_id??e.execution_id??e.conversation_id??e.id),started_at:String(e.occurred_at??e.started_at??`1970-01-01T00:00:00.000Z`),finished_at:typeof e.finished_at==`string`?e.finished_at:null,task_id:typeof e.task_id==`string`?e.task_id:null,execution_id:typeof e.execution_id==`string`?e.execution_id:null,conversation_id:typeof e.conversation_id==`string`?e.conversation_id:null,parent_run_id:typeof e.parent_agent_invocation_id==`string`?e.parent_agent_invocation_id:null,run_kind:e.invocation_kind===`delegated`||e.invocation_kind===`subagent`?`subrun`:e.invocation_kind===`orchestrator`?`run`:null,run_purpose:typeof e.purpose==`string`?e.purpose:null,phase:typeof e.phase==`string`?e.phase:null,status:typeof e.status==`string`?e.status:null,agent:typeof e.zaip_agent==`string`?e.zaip_agent:null,agent_persona:typeof e.zaip_agent_persona==`string`?e.zaip_agent_persona:null,agent_job:typeof e.zaip_agent_job==`string`?e.zaip_agent_job:null,client:typeof e.client==`string`?e.client:null,provider:typeof e.provider==`string`?e.provider:null,model:typeof e.model==`string`?e.model:null,reasoning_effort:typeof e.reasoning_effort==`string`?e.reasoning_effort:null,service_tier:typeof e.service_tier==`string`?e.service_tier:null,duration_ms:typeof e.duration_ms==`number`?e.duration_ms:typeof e.total_duration==`number`?e.total_duration:null,source_duration_ms:typeof e.source_duration_ms==`number`?e.source_duration_ms:null,duration_provenance:typeof e.duration_provenance==`string`?e.duration_provenance:null,llm_call_count:typeof e.llm_call_count==`number`?e.llm_call_count:null,input_tokens:typeof e.input_tokens==`number`?e.input_tokens:null,cached_input_tokens:typeof e.cached_input_tokens==`number`?e.cached_input_tokens:null,uncached_input_tokens:typeof e.uncached_input_tokens==`number`?e.uncached_input_tokens:null,output_tokens:typeof e.output_tokens==`number`?e.output_tokens:null,reasoning_tokens:typeof e.reasoning_tokens==`number`?e.reasoning_tokens:null,visible_output_tokens:typeof e.visible_output_tokens==`number`?e.visible_output_tokens:null,total_tokens:typeof e.total_tokens==`number`?e.total_tokens:null,input_rate_usd_per_million:typeof e.input_rate_usd_per_million==`number`?e.input_rate_usd_per_million:null,cached_input_rate_usd_per_million:typeof e.cached_input_rate_usd_per_million==`number`?e.cached_input_rate_usd_per_million:null,output_rate_usd_per_million:typeof e.output_rate_usd_per_million==`number`?e.output_rate_usd_per_million:null,reasoning_rate_usd_per_million:typeof e.reasoning_rate_usd_per_million==`number`?e.reasoning_rate_usd_per_million:null,context_input_multiplier:typeof e.context_input_multiplier==`number`?e.context_input_multiplier:null,context_output_multiplier:typeof e.context_output_multiplier==`number`?e.context_output_multiplier:null,speed_cost_multiplier:typeof e.speed_cost_multiplier==`number`?e.speed_cost_multiplier:null,pricing_scenario:typeof e.pricing_scenario==`string`?e.pricing_scenario:null,standard_cost_usd:typeof e.standard_cost_usd==`number`?e.standard_cost_usd:null,speed_uplift_usd:typeof e.speed_uplift_usd==`number`?e.speed_uplift_usd:null,input_cost_usd:typeof e.input_cost_usd==`number`?e.input_cost_usd:null,cached_input_cost_usd:typeof e.cached_input_cost_usd==`number`?e.cached_input_cost_usd:null,output_cost_usd:typeof e.output_cost_usd==`number`?e.output_cost_usd:null,reasoning_cost_usd:typeof e.reasoning_cost_usd==`number`?e.reasoning_cost_usd:null,calculated_cost_usd:typeof e.calculated_cost_usd==`number`?e.calculated_cost_usd:null,recorded_cost_usd:typeof e.recorded_cost_usd==`number`?e.recorded_cost_usd:null,cost_variance_usd:typeof e.cost_variance_usd==`number`?e.cost_variance_usd:null,cost_usd:typeof e.cost_usd==`number`?e.cost_usd:null,fx_rate:typeof e.fx_rate==`number`?e.fx_rate:null,pricing_segment_count:typeof e.pricing_segment_count==`number`?e.pricing_segment_count:null,pricing_mixed:e.pricing_mixed===1||e.pricing_mixed===!0,pricing_model:typeof e.audit_pricing_model==`string`?e.audit_pricing_model:typeof e.pricing_model==`string`?e.pricing_model:null,pricing_source:typeof e.audit_pricing_source==`string`?e.audit_pricing_source:typeof e.pricing_source==`string`?e.pricing_source:null,cost:typeof e.total_cost_brl==`number`?e.total_cost_brl:typeof e.cost_brl==`number`?e.cost_brl:null,currency:`BRL`}))};if(!_())return;l(e=>e===null?e:bt(e,u,r)),s({offset:r.offset,total:r.total,loading:!1,error:null,aggregation:r.aggregation})}catch(e){if(!_()||E(e))return;s({offset:d,total:null,loading:!1,error:e instanceof Error?e.message:String(e)})}finally{n.current===p&&(n.current=null)}},[e,t,n,r,i,a,o,s,c,l]),loadOperationsLifecyclePage:(0,m.useCallback)(async(u,d=0,f=t.current)=>{n.current?.abort();let p=new AbortController;n.current=p;let m=++r.current,h=o.current,g=R(i),_=()=>O(m,r.current,p.signal)&&T(h,o.current,g,R(a.current));c(u),s({offset:d,total:null,loading:!0,error:null});try{let t=await e.sqliteViewPage(u===`changes`?`operations_changes`:`operations_decisions`,g,{offset:d,limit:100,...f.query?{query:f.query}:{},...f.status?{status:f.status}:{},...f.risk?{risk:f.risk}:{}},p.signal),n=u===`changes`?t.rows.map(e=>{let t=String(e.source_type),n=String(e.source_id);return{id:String(e.id),title:typeof e.title==`string`?e.title:String(e.id),created_at:typeof e.occurred_at==`string`?e.occurred_at:null,status:typeof e.status==`string`?e.status:`unclassified`,risk:typeof e.risk==`string`?e.risk:`unclassified`,source:t===`spec`?{type:`spec`,spec_id:n}:t===`prd`?{type:`prd`,prd_id:n,spec_id:null}:{type:`task`,task_id:n},requirement_ids:J(e.requirement_ids_json),acceptance_ids:J(e.acceptance_ids_json),task_ids:J(e.task_ids_json),result:typeof e.result==`string`?e.result:null,artifact_path:typeof e.source_path==`string`?e.source_path:String(e.id)}}):t.rows.map(e=>({id:String(e.id),title:typeof e.title==`string`?e.title:String(e.id),origin:e.origin===`human`?`human`:`agent`,scope_type:e.scope_type===`execution`?`execution`:`change`,scope_id:String(e.scope_id),artifact_path:typeof e.source_path==`string`?e.source_path:String(e.id),created_at:typeof e.occurred_at==`string`?e.occurred_at:`1970-01-01T00:00:00.000Z`})),r={kind:u,offset:t.offset,limit:t.limit,total:t.total_count,rows:n};if(!_())return;l(e=>e===null?e:{...e,...u===`changes`?{changes:r.rows}:{decisions:r.rows}}),s({offset:r.offset,total:r.total,loading:!1,error:null})}catch(e){if(!_()||E(e))return;s({offset:d,total:null,loading:!1,error:e instanceof Error?e.message:String(e)})}finally{n.current===p&&(n.current=null)}},[e,t,n,r,i,a,o,s,c,l])}}function St({api:e,operations:t,setError:n,setFailedArea:r,setLoadingArea:i}){let[a,o]=(0,m.useState)(null),[s,c]=(0,m.useState)([]),[l,u]=(0,m.useState)(null),[d,f]=(0,m.useState)(null),p=(0,m.useRef)(0),h=(0,m.useRef)(0),g=(0,m.useRef)(null),[_,v]=(0,m.useState)(null),[y,b]=(0,m.useState)(``);async function x(a){let c=++h.current;g.current?.abort();let l=new AbortController;g.current=l,n(null),r(null),o(null),v(a),i(`traceability`),await new Promise(e=>window.requestAnimationFrame(()=>e()));try{let n=await e.taskTrace(a,l.signal);if(h.current!==c)return!1;let r=s.find(e=>e.id===a)??t?.tasks.find(e=>e.id===a);return o({...n,task_title:r?.title||n.task_title||a,task_risk:r?.risk||n.task_risk||null,task_created_at:r?.created_at||n.task_created_at||null,task_progress:n.task_progress??r?.progress??0}),!0}catch(e){return l.signal.aborted||h.current!==c?!1:(n(e instanceof Error?e.message:String(e)),r(`traceability`),!1)}finally{h.current===c&&(g.current===l&&(g.current=null),v(null),i(e=>e===`traceability`?null:e))}}function S(e){let n=t?.changes.find(t=>t.id===e);n!==void 0&&(o(null),f({kind:`change`,row:n}))}function C(e,n){let r=(e===`PRD`?t?.prds:t?.specs)?.find(e=>e.id===n);r!==void 0&&(o(null),f({kind:`macro`,label:e,row:r}))}async function w(n,r){let i=(n===`prd`?t?.prds:t?.specs)?.find(e=>e.id===r);if(!i)return;let a=++p.current,o=n===`prd`?`PRD`:`SPEC`;u({kind:n,label:o,preview:i});try{let t=n===`prd`?await e.prd(r):await e.spec(r);if(p.current!==a)return;u({kind:n,label:o,preview:i,detail:t})}catch(e){if(p.current!==a)return;u({kind:n,label:o,preview:i,error:e instanceof Error?e.message:String(e)})}}function T(){p.current+=1,u(null)}return{closeDocument:T,documentDetail:l,openDocument:w,openTrace:x,openTraceChange:S,openTraceMacro:C,selectedTraceTaskId:y,setSelectedTraceTaskId:b,setTrace:o,setTraceLink:f,setTraceLoadingTaskId:v,setTraceTasks:c,trace:a,traceLink:d,traceLoadingTaskId:_,traceTasks:s}}function Ct({cursor:e,page:t,tasks:n}){let r=new Map(n.map(e=>[e.id,e]));for(let e of t.tasks)r.set(e.id,e);let i=e.offset+t.tasks.length;return{tasks:[...r.values()],cursor:t.tasks.length===0||i>=t.total?{offset:0,stageIndex:e.stageIndex+1}:{...e,offset:i}}}function wt(e,t,n){return Math.min(t,e+n)}function Tt(e,t,n){let r=(0,m.useRef)(t),i=(0,m.useRef)({offset:0,stageIndex:0}),a=(0,m.useRef)(!1),[o,s]=(0,m.useState)(!1),[c,l]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{r.current=t},[t]),{loadMoreTraceTasks:(0,m.useCallback)(async(t=!1,o=!1)=>{if(a.current||(o&&(i.current={offset:0,stageIndex:0},r.current=[],n([]),s(!0)),i.current.stageIndex>=1))return r.current;a.current=!0,l(!0);try{do{let a=i.current,o=await e.traceabilityTasks(a.offset,10),s=Ct({cursor:a,page:o,tasks:r.current});if(r.current=s.tasks,n(r.current),i.current=s.cursor,o.tasks.length>0&&!t)break}while(i.current.stageIndex<1);return s(i.current.stageIndex<1),r.current}finally{a.current=!1,l(!1)}},[e,n]),traceTasksHasMore:o,traceTasksLoading:c}}function Et({api:e,boardAbortControllersRef:t,boardFilterKeyRef:n,boardFiltersRef:r,boardInFlightRef:i,boardInitialPageRef:a,boardLoadedRef:o,boardRequestVersionRef:s,dashboardView:c,operations:l,operationsPeriod:u,operationsPeriodRef:d,overviewStatusInFlightRef:f,quickOverviewMetricsRef:p,setBoardKindTotals:h,setBoardStates:g,setBoardTotals:_,setOperations:v,setOverviewClassificationPages:y,setOverviewStatusPages:b}){let x=(0,m.useCallback)(()=>{s.current+=1;for(let e of t.current.values())e.abort();t.current.clear(),i.current.clear(),a.current.clear(),o.current={},_({}),h({}),g({}),b({}),y({})},[t,i,a,o,s,h,g,_,y,b]),S=(0,m.useCallback)(async n=>{if(l===null||i.current.has(n))return;i.current.add(n),t.current.get(n)?.abort();let a=new AbortController;t.current.set(n,a);let c=s.current,f=R(u);g(e=>({...e,[n]:{loading:!0,error:null}}));let p=o.current[n]??0;try{let t=await e.operationsBoard(f,n,p,r.current,a.signal,10);if(a.signal.aborted||c!==s.current||f.from!==R(d.current).from||f.to!==R(d.current).to)return;v(e=>e===null?e:{...k(e,[t]),summary:e.summary}),_(e=>({...e,[n]:t.total})),h(e=>({...e,[n]:t.totals_by_kind})),o.current={...o.current,[n]:p+t.prds.length+t.specs.length+t.tasks.length}}catch(e){if(a.signal.aborted||c!==s.current||E(e))return;g(t=>({...t,[n]:{loading:!1,error:e instanceof Error?e.message:String(e)}}))}finally{c===s.current&&(i.current.delete(n),t.current.get(n)===a&&t.current.delete(n),g(e=>e[n]?.error===null?{...e,[n]:{loading:!1,error:null}}:e))}},[e,t,r,i,o,s,l,u,d,h,g,_,v]),C=(0,m.useCallback)(e=>{let t={...e,kind:e.kind??r.current.kind??``},i=`${t.query}|${t.status}|${t.risk}|${t.origin??``}|${t.kind}`;i!==n.current&&(n.current=i,r.current=t,x(),v(e=>e===null?e:{...e,prds:[],specs:[],tasks:[],changes:[],summary:i===`||||`&&p.current!==void 0?{...e.summary,overview_metrics:p.current}:e.summary}))},[n,r,p,x,v]),w=(0,m.useCallback)(async(t,n,r)=>{let i=Ce(t,n),a=f.current;if(a.has(i))return;a.add(i);let o=s.current,c=R(u);b(e=>({...e,[i]:{items:r===0?[]:e[i]?.items??[],total:e[i]?.total??0,loading:!0,error:null}}));try{let a=await e.operationsBoard(c,t,r,{kind:n===`task`?`all-tasks`:n});if(o!==s.current||c.from!==R(d.current).from||c.to!==R(d.current).to)return;let l=n===`task`?a.tasks:n===`spec`?a.specs:a.prds;b(e=>({...e,[i]:{items:r===0?l:[...e[i]?.items??[],...l],total:a.total,loading:!1,error:null}}))}catch(e){if(o!==s.current||E(e))return;b(t=>({...t,[i]:{items:t[i]?.items??[],total:t[i]?.total??0,loading:!1,error:e instanceof Error?e.message:String(e)}}))}finally{a.delete(i)}},[e,s,u,d,f,b]),T=(0,m.useCallback)(async(t,n,r)=>{let i=we(t,n),a=f.current;if(a.has(i))return;a.add(i);let o=s.current,c=R(u);y(e=>({...e,[i]:{items:r===0?[]:e[i]?.items??[],total:e[i]?.total??0,loading:!0,error:null}}));try{let a=await e.operationsClassification(c,t,n,r);if(o!==s.current||c.from!==R(d.current).from||c.to!==R(d.current).to)return;let l=t===`task`?a.tasks:t===`spec`?a.specs:a.prds;y(e=>({...e,[i]:{items:r===0?l:[...e[i]?.items??[],...l],total:a.total,loading:!1,error:null}}))}catch(e){if(o!==s.current||E(e))return;y(t=>({...t,[i]:{items:t[i]?.items??[],total:t[i]?.total??0,loading:!1,error:e instanceof Error?e.message:String(e)}}))}finally{a.delete(i)}},[e,s,u,d,f,y]),D=(0,m.useCallback)(t=>{let n={...r.current,...t},i=R(u);return{prepare:async()=>{let t=await Promise.all(Te.map(t=>e.operationsBoard(i,t,0,n))),r=e=>[...e.prds.map(({kind:e,...t})=>({kind:`prd`,...t})),...e.specs.map(({kind:e,...t})=>({kind:`spec`,...t})),...e.tasks.map(e=>({kind:`task`,...e}))];return{totalRows:t.reduce((e,t)=>e+t.total,0),pages:async function*(){for(let a of t){let t=a,o=0;for(;;){let a=r(t);if(a.length===0||(o+=a.length,yield a,o>=t.total))break;t=await e.operationsBoard(i,t.stage,o,n)}}}}}}},[e,r,u]);return(0,m.useEffect)(()=>{if(c!==`operations`||l===null)return;let e=!1,t=s.current,n=()=>!e&&t===s.current,r=async()=>{if(!n())return;let e=Te.filter(e=>!a.current.has(e)&&!i.current.has(e));for(let t=0;t<e.length&&n();t+=3){let r=e.slice(t,t+3);if(!n())return;for(let e of r)a.current.add(e);await Promise.all(r.map(e=>S(e)))}},o=window.setTimeout(()=>void r(),0);return()=>{e=!0,window.clearTimeout(o)}},[i,a,s,c,S,l]),{boardExportSource:D,loadFilteredBoard:C,loadMoreBoard:S,loadOverviewClassificationPage:T,loadOverviewStatusPage:w,resetBoard:x}}function Y(e,t){return JSON.stringify([e.query,e.status,e.risk,e.origin??``,e.kind??``,t.from??``,t.to??``])}function Dt(e,t,n){return e===`explicit`||t!==n}function X(e,t){return{...e,kind:e.kind??t.kind??``}}var Z={offset:0,limit:10,total:null,hasMore:!1,typeFilter:`all`,rows:[],loading:!1,error:null};function Ot({api:e,operationsPeriod:t,operationsPeriodRef:n}){let[r,i]=(0,m.useState)(Z),a=(0,m.useRef)({query:``,status:``,risk:``}),o=(0,m.useRef)(null),s=(0,m.useRef)(0),c=(0,m.useRef)(null),l=(0,m.useCallback)(async(r,l=0,u=`explicit`)=>{let d=R(t),f=X(r,a.current),p=Y(f,d);if(!Dt(u,p,c.current))return;o.current?.abort();let m=new AbortController;o.current=m;let h=++s.current;a.current=f,c.current=p;let g=f.kind||`all`;i(e=>({...e,offset:l,typeFilter:g,loading:!0,error:null}));try{let t=await e.sqliteViewPage(`operations_work_list`,d,{offset:l,limit:10,...f.query?{query:f.query}:{},...f.status?{status:f.status}:{},...f.risk?{risk:f.risk}:{},...f.origin?{origin:f.origin}:{},...g===`all`?{}:{kind:g}},m.signal);if(m.signal.aborted||h!==s.current||d.from!==R(n.current).from||d.to!==R(n.current).to)return;i({offset:t.offset,limit:t.limit,total:t.total_count,hasMore:t.has_more,typeFilter:g,rows:t.rows,loading:!1,error:null})}catch(e){if(m.signal.aborted||h!==s.current)return;c.current===p&&(c.current=null),i(t=>({...t,offset:l,typeFilter:g,loading:!1,error:e instanceof Error?e.message:String(e)}))}finally{o.current===m&&(o.current=null)}},[e,t,n]),u=(0,m.useCallback)(()=>{o.current?.abort(),o.current=null,++s.current,c.current=null,i(Z)},[]);return{workListPage:r,workListFiltersRef:a,loadWorkListFilters:(0,m.useCallback)(e=>l(e,0,`filter-hydration`),[l]),loadWorkListPage:l,resetWorkListPage:u}}async function*kt(e,t){let n=e;for(;;){if(n.rows.length===0)return;yield n.rows;let e=n.offset+n.rows.length;if(!n.has_more||e>=n.total_count)return;n=await t(e)}}function At({api:e,operationsPeriod:t}){return(0,m.useCallback)((n,r)=>{let i=R(t);if(n===`work-kanban`)return;let a={"work-list":`operations_work_list`,changes:`operations_changes`,decisions:`operations_decisions`,executions:`operations_executions`,runs:`operations_agent_invocations`,conversations:`operations_conversations`,daily:`operations_daily`,monthly:`operations_monthly`,yearly:`operations_annual`}[n];if(a===void 0)return;let o=e=>({offset:e,limit:100,...r.query?{query:r.query}:{},...r.status?{status:r.status}:{},...r.risk?{risk:r.risk}:{},...r.origin?{origin:r.origin}:{},...a===`operations_work_list`&&r.kind?{kind:r.kind}:{}});return{prepare:async()=>{let t=await e.sqliteViewPage(a,i,o(0));return{totalRows:t.total_count,pages:()=>kt(t,t=>e.sqliteViewPage(a,i,o(t)))}}}},[e,t])}var jt=1500;function Q({snapshotUpdating:e,initialDataPending:t,dismissed:n,delayElapsed:r}){return e&&t&&!n&&r}function Mt(e,t,n){let[r,i]=(0,m.useState)(!1),[a,o]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{if(!e||!t||r){o(!1);return}let n=window.setTimeout(()=>o(!0),jt);return()=>window.clearTimeout(n)},[t,r,e]),Q({snapshotUpdating:e,initialDataPending:t,dismissed:r,delayElapsed:a})?(0,g.jsxs)(`div`,{"aria-live":`polite`,className:`app-notice app-snapshot-status`,role:`status`,children:[(0,g.jsx)(`span`,{children:`Exibindo o último snapshot local validado. Os dados canônicos estão sendo atualizados em segundo plano e estarão atuais na próxima abertura.`}),(0,g.jsx)(`button`,{"aria-label":n===`pt-BR`?`Fechar aviso de atualização do snapshot`:`Dismiss snapshot update notice`,onClick:()=>i(!0),type:`button`,children:`×`})]}):null}function Nt(){Be(je());let[e,t]=(0,m.useState)(!1),n=(0,m.useMemo)(je,[]),r=(0,m.useMemo)(()=>new Me(n),[n]),{loadCostDetail:i,loadCostReadModelPage:a,loadCostRunPage:o,loadCostGroupPage:s}=at(r),[c,l]=(0,m.useState)(()=>Ae(window.location.pathname)),u=(0,m.useRef)(c);u.current=c;let[d,f]=(0,m.useState)(null),[p,h]=(0,m.useState)({offset:0,total:null,loading:!1,error:null}),[g,_]=(0,m.useState)(`runs`),v=(0,m.useRef)({query:``,status:``,risk:``}),[y,b]=(0,m.useState)({}),[x,O]=(0,m.useState)({}),[k,ee]=(0,m.useState)({}),[te,ne]=(0,m.useState)({}),[re,A]=(0,m.useState)({}),[j,M]=(0,m.useState)(null),[ie,N]=(0,m.useState)(null),[P,ae]=(0,m.useState)(ke),[F,oe]=(0,m.useState)(()=>window.localStorage.getItem(`zaip-dashboard-currency`)===`USD`?`USD`:`BRL`),se=(0,m.useRef)(F);se.current=F;let ce=(0,m.useCallback)(e=>{ae(e),oe(e===`en-US`?`USD`:`BRL`)},[]),[I,le]=(0,m.useState)(()=>be),ue=I.preset===`all`?null:I.range.start,de=I.preset===`all`?null:I.range.end,fe=(0,m.useMemo)(()=>({from:ue,to:de}),[ue,de]),L=(0,m.useRef)(I);L.current=I;let pe=(0,m.useRef)(null),[me,he]=(0,m.useState)(!1),[ge,_e]=(0,m.useState)(null),[ve,ye]=(0,m.useState)(null),[xe,Se]=(0,m.useState)(window.location.pathname),[Te,Ee]=(0,m.useState)(!0),[z,De]=(0,m.useState)(!1),[,Oe]=(0,m.useState)(!1),[,Ne]=(0,m.useState)(!1),[Pe,B]=(0,m.useState)(`operations`),[V,H]=(0,m.useState)(null),[Fe,U]=(0,m.useState)(null);(0,m.useEffect)(()=>{r.captureTelemetry().then(()=>r.ready()).then(e=>t(e.snapshot_state===`updating`)).catch(()=>{})},[r]);let[Le,W]=(0,m.useState)(null),[Re,ze]=(0,m.useState)(null),[G,K]=(0,m.useState)(null),[Qe,$e]=(0,m.useState)(Ge),et=(0,m.useCallback)(e=>{$e(t=>Ke(t,e))},[]);(0,m.useEffect)(()=>{let e=!1;return r.dashboardIdentity().then(t=>{e||et(t)}).catch(()=>{}),()=>{e=!0}},[r,et]);let{closeDocument:tt,documentDetail:nt,openDocument:rt,openTrace:it,openTraceChange:ot,openTraceMacro:st,selectedTraceTaskId:ct,setSelectedTraceTaskId:lt,setTrace:ut,setTraceLink:dt,setTraceLoadingTaskId:ft,setTraceTasks:pt,trace:mt,traceLink:ht,traceLoadingTaskId:gt,traceTasks:_t}=St({api:r,operations:d,setError:W,setFailedArea:H,setLoadingArea:B}),{loadMoreTraceTasks:vt,traceTasksHasMore:q,traceTasksLoading:bt}=Tt(r,_t,pt),J=(0,m.useRef)(0),Ct=(0,m.useRef)(0),wt=(0,m.useRef)(!1),Y=(0,m.useRef)(0),Dt=(0,m.useRef)(0),X=(0,m.useRef)(null),Z=(0,m.useRef)(!1),kt=(0,m.useRef)(!1),jt=(0,m.useRef)(null),Q=(0,m.useRef)(null),Nt=(0,m.useRef)(null),Pt=(0,m.useRef)(0),Ft=(0,m.useRef)({}),It=(0,m.useRef)(new Set),Lt=(0,m.useRef)(new Map),Rt=(0,m.useRef)(new Set),zt=(0,m.useRef)(new Set),Bt=(0,m.useRef)({query:``,status:``,risk:``,origin:``,kind:``}),Vt=(0,m.useRef)(`||||`),Ht=(0,m.useRef)(0),Ut=(0,m.useRef)(void 0),{workListPage:Wt,workListFiltersRef:Gt,loadWorkListFilters:Kt,loadWorkListPage:qt,resetWorkListPage:Jt}=Ot({api:r,operationsPeriod:I,operationsPeriodRef:L}),Yt=(0,m.useRef)(!1),$=(0,m.useCallback)(async(e=!0,n=!1,i=!1,a=!1)=>{jt.current?.(),jt.current=null,Q.current?.abort(),Q.current=null,Ht.current+=1;for(let e of Lt.current.values())e.abort();Lt.current.clear(),It.current.clear(),zt.current.clear(),Ft.current={},b({}),O({}),ee({}),ne({}),A({});let o=++J.current,s=Ct.current,c=u.current,l=fe,d=()=>w(o,J.current)&&T(o,J.current,l,R(L.current));e&&(Ee(!0),B(`operations`)),W(null),H(null);try{if(n){let e=await r.reconcileOpenWork(F,l),n=Ie(e,d());if(ze(n.reconciliation),n.dismissProgressDialog&&U(null),!n.applySnapshotState)return!1;if(t(e.snapshot_state===`updating`),n.reloadQuickProjection){let e=await r.operations(l,`quick`,void 0,!0);if(!d())return!1;Yt.current=!1,f(e),Ut.current=e.summary.overview_metrics,kt.current=!1,K(e.summary.latest_token_collected_at??null)}}else if(i){let e=await r.refreshProjection(F,l);if(!d())return!1;f(e.operations),Ut.current=e.operations.summary.overview_metrics,kt.current=!0,M(e.costs),Z.current=!0,N(null);let t=e.dashboard;t&&$e(e=>Ke(e,t)),K(e.projection.latest_token_collected_at??null)}else{let[e,t]=await Promise.all([r.operations(l,`quick`,void 0,Yt.current),F===`USD`||a?r.costMonitor(F,l,`summary`):Promise.resolve(null)]);if(!d())return!1;Yt.current=!1,f(e),Ut.current=e.summary.overview_metrics,kt.current=!1,t!==null&&(M(t),Z.current=!1,N(null)),K(e.summary.latest_token_collected_at??null)}return!0}catch(e){return d()?(W(e instanceof Error?e.message:String(e)),H(c===`cost-monitor`?`costs`:`operations`),!1):!1}finally{d()&&D(s,Ct.current)&&Ne(!1),e&&d()&&(Ee(!1),B(e=>e===`operations`?null:e))}},[r,F,fe]),Xt=(0,m.useCallback)(async e=>{if(kt.current||wt.current||e?.aborted)return null;Q.current?.abort();let t=e===void 0?new AbortController:null,n=e??t?.signal;if(n===void 0)return null;t!==null&&(Q.current=t),wt.current=!0,Y.current+=1,B(`costs`),H(null);try{let e=++J.current,t=R(I),i=()=>w(e,J.current)&&T(e,J.current,t,R(L.current)),a=await r.operations(t,`detail`,n);return i()?(f(a),kt.current=!0,a):null}catch(e){return n.aborted||E(e)?null:(W(e instanceof Error?e.message:String(e)),H(`operations`),null)}finally{t!==null&&Q.current===t&&(Q.current=null),wt.current=!1,Y.current=Math.max(0,Y.current-1),Y.current===0&&B(e=>e===`costs`?null:e)}},[r,I]),{loadOperationsEntityPage:Zt,loadOperationsLifecyclePage:Qt}=xt({api:r,entityFiltersRef:v,operationsPageAbortRef:Nt,operationsPageRequestVersionRef:Pt,operationsPeriod:I,operationsPeriodRef:L,refreshVersion:J,setEntityPage:h,setEntityPageKind:_,setOperations:f}),$t=(0,m.useCallback)((e,t)=>{v.current=t,e===`changes`||e===`decisions`?Qt(e,0,t):Zt(e,0,t)},[Zt,Qt]),{boardExportSource:en,loadFilteredBoard:tn,loadMoreBoard:nn,loadOverviewClassificationPage:rn,loadOverviewStatusPage:an,resetBoard:on}=Et({api:r,boardAbortControllersRef:Lt,boardFilterKeyRef:Vt,boardFiltersRef:Bt,boardInFlightRef:It,boardInitialPageRef:zt,boardLoadedRef:Ft,boardRequestVersionRef:Ht,dashboardView:c,operations:d,operationsPeriod:I,operationsPeriodRef:L,overviewStatusInFlightRef:Rt,quickOverviewMetricsRef:Ut,setBoardKindTotals:O,setBoardStates:ee,setBoardTotals:b,setOperations:f,setOverviewClassificationPages:A,setOverviewStatusPages:ne}),sn=At({api:r,operationsPeriod:I}),cn=async e=>{e&&ze(null),U(e?`reconciling`:`refreshing`);try{await $(!1,e,!e)}finally{U(null)}};(0,m.useEffect)(()=>{let e=null,t=()=>{e=window.setTimeout(()=>{le(e=>{let t=Xe(e);return t!==e&&(pe.current=t),t}),t()},Ze())};return t(),()=>{e!==null&&window.clearTimeout(e)}},[]),(0,m.useEffect)(()=>{pe.current===I&&(pe.current=null,$(!1,!1,!0,!0))},[I,$]),yt({api:r,costLocale:P,currency:F,dashboardView:c,loadOperationsDetails:Xt,operations:d,operationsDetailAbortRef:Q,operationsDetailCancelRef:jt,operationsPageAbortRef:Nt,pathname:xe,pricing:ge,refresh:$,refreshVersion:J,setSnapshotUpdating:t,setError:W,setFxRate:ye,setPathname:Se,setPricing:_e,snapshotUpdating:e});let ln=He(Se),un=(0,m.useCallback)(async()=>{X.current?.abort();let e=new AbortController;X.current=e;let t=++Dt.current,n=R(I);Y.current+=1,B(`costs`),W(null),H(null);try{let i=await r.costMonitor(F,n,`summary`,e.signal),a=R(L.current);if(!C({aborted:e.signal.aborted,currentCurrency:se.current,currentPeriod:a,currentRequestVersion:Dt.current,requestVersion:t,requestedCurrency:F,requestedPeriod:n}))return;M(i),Z.current=!0,N(null)}catch(n){if(e.signal.aborted||t!==Dt.current)return;W(n instanceof Error?n.message:String(n)),H(`costs`)}finally{Y.current=Math.max(0,Y.current-1),Y.current===0&&B(e=>e===`costs`?null:e),X.current===e&&(X.current=null)}},[r,F,I]);(0,m.useEffect)(()=>{F!==`USD`||j?.currency===F||un()},[j?.currency,F,un]),(0,m.useEffect)(()=>{d===null||V===`costs`||X.current!==null||S({costsLoaded:Z.current,currency:F,snapshotCurrency:j?.currency})&&un()},[j?.currency,F,V,un,d]);let dn=Ye({setDashboardView:l,costsLoadedRef:Z,currency:F,costs:j,loadCostSummary:un,costSummaryAbortRef:X,traceTasks:_t,boardRequestVersionRef:Ht,loadMoreTraceTasks:vt,setTraceTasks:pt,setSelectedTraceTaskId:lt,openTrace:it,setTrace:ut,setTraceLoadingTaskId:ft}),fn=Ue(j,ie,F),{fact:pn,periods:mn}=We(j,ie,F),hn=()=>qe(V,ct,d,un,it,Xt,$,W),gn=Je(r,P,ve,ln,xe,ge,$,ye,_e);return{loadMoreBoard:nn,overviewStatusPageKey:Ce,overviewClassificationPageKey:we,boardRequestVersionRef:Ht,boardAbortControllersRef:Lt,boardInFlightRef:It,boardInitialPageRef:zt,boardLoadedRef:Ft,setBoardTotals:b,setBoardKindTotals:O,setBoardStates:ee,setOverviewStatusPages:ne,setOverviewClassificationPages:A,setOperationsLoading:Ee,operations:d,error:Le,globalLoadingPending:F===`USD`&&j?.currency!==F,costLocale:P,refresh:async()=>{await $()},snapshotNotice:Mt(e,d===null&&Te,P),setupRoute:gn,failedArea:V,retryLastLoad:hn,costs:j,currency:F,dashboardView:c,lastUpdatedAt:G,loadCostDetail:i,loadCostReadModelPage:a,loadCostRunPage:o,loadCostGroupPage:s,loadingArea:Pe,setDisplayedCosts:N,setCurrency:oe,setCostSurfaceLoading:Oe,changeDashboardLocale:ce,loadMoreTraceTasks:vt,openTrace:it,setRefreshDialog:U,setSelectedTraceTaskId:lt,openTraceChange:ot,openTraceMacro:st,selectedTraceTaskId:ct,trace:mt,traceLoadingTaskId:gt,traceTasksHasMore:q,traceTasksLoading:bt,traceTasks:_t,capabilityNavigation:Ve(c,P,e=>void dn(e)),boardTotals:y,boardKindTotals:x,boardExportSource:en,detailExportSource:sn,boardStates:k,operationsPeriod:I,entityPage:p,dashboardIdentity:Qe,operationsLoading:Te,factualCostFact:pn,factualCostPeriods:mn,setOperationsSurfaceLoading:De,operationsSurfaceLoading:z,currentCostByRun:fn,loadOperationsEntityPage:Zt,loadOperationsLifecyclePage:Qt,loadOperationsDetails:Xt,entityPageKind:g,loadFilteredOperationsPage:$t,loadFilteredBoard:tn,loadWorkListPage:qt,loadWorkListFilters:Kt,workListFiltersRef:Gt,boardFiltersRef:Bt,workListPage:Wt,overviewStatusPages:te,loadOverviewStatusPage:an,overviewClassificationPages:re,loadOverviewClassificationPage:rn,openDocument:rt,api:r,setError:W,operationsPeriodRef:L,setOperationsPeriod:le,operationsDetailLoadedRef:kt,operationsDetailCancelRef:jt,operationsDetailAbortRef:Q,operationsPageAbortRef:Nt,resetWorkListPage:Jt,operationsPageRequestVersionRef:Pt,resetBoard:on,refreshVersion:J,costSummaryAbortRef:X,costSummaryRequestVersion:Dt,setEntityPage:h,costsLoadedRef:Z,setCosts:M,setPeriodTransitionPending:Ne,periodTransitionVersionRef:Ct,setLoadingArea:B,navigate:ln,setHelpOpen:he,closeDocument:tt,documentDetail:nt,helpOpen:me,reconciliationResult:Re,setReconciliationResult:ze,refreshDialog:Fe,setTrace:ut,traceLink:ht,setTraceLoadingTaskId:ft,setTraceLink:dt,refreshFromDialog:cn,renderedOperations:d}}async function Pt(e){let t=await(await fetch(`/api/v2/health`,{cache:`no-store`,signal:e})).json();if(t?.kind!==`zaip-dashboard-sqlite-runtime`||typeof t.workspace!=`string`||typeof t.workspace_name!=`string`||![`initialized`,`missing`,`invalid`].includes(t.lifecycle_manifest_state))throw Error(`Identidade do Dashboard indisponível`);return t}function Ft(){let[e,t]=(0,m.useState)(null),[n,r]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{let e=!1,n,i;async function a(){i=new AbortController;let o=setTimeout(()=>i.abort(),4e3);try{let n=await Pt(i.signal);e||(t(n),r(!1))}catch{e||r(!0)}finally{clearTimeout(o),e||(n=setTimeout(a,5e3))}}return a(),()=>{e=!0,clearTimeout(n),i?.abort()}},[]),{status:e,unavailable:n}}function It({status:e,unavailable:t=!1}){let n=e?.lifecycle_manifest_state;return n===`initialized`&&e?.status===`ok`&&!t?null:(0,g.jsx)(`aside`,{className:`workspace-status`,"aria-label":`Saúde do Dashboard`,children:n===`missing`||n===`invalid`?(0,g.jsxs)(`div`,{className:`workspace-status__warning`,role:`alert`,children:[(0,g.jsx)(`strong`,{children:n===`missing`?`Lifecycle não inicializado`:`Manifesto do lifecycle inválido`}),(0,g.jsx)(`p`,{children:`Os dados deste workspace estão indisponíveis. Na pasta do projeto, execute:`}),(0,g.jsx)(`code`,{children:`node .agents/runtime/bin/zaip.mjs manifest rebuild --confirm-full-scan`})]}):e?.status===`degraded`||t?(0,g.jsx)(`p`,{className:`workspace-status__warning`,role:`status`,children:t?`Não foi possível consultar a saúde do Dashboard. Tentando novamente…`:`Dashboard degradado: a atualização dos dados ou da telemetria requer atenção.`}):(0,g.jsx)(`p`,{className:`workspace-status__warning`,role:`status`,children:`Identificando a saúde do Dashboard…`})})}function Lt(){let e=Nt(),t=Ft();return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(It,{...t}),t.status?.lifecycle_manifest_state===`initialized`?(0,g.jsx)(Se,{model:e}):null]})}var Rt=document.getElementById(`root`);if(!Rt)throw Error(`Elemento #root não encontrado`);(0,h.createRoot)(Rt).render((0,g.jsx)(m.StrictMode,{children:(0,g.jsx)(Lt,{})}));export{wt as n,Ft as t};