@zaip-ai/cli 5.7.0 → 5.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/services/adapters.d.ts +1 -1
- package/dist/services/adapters.js +1 -1
- package/package.json +1 -1
- package/templates/.agents/README-ENG.md +2 -0
- package/templates/.agents/README.md +2 -0
- package/templates/.agents/config/agents/discovery.json +1 -1
- package/templates/.agents/dashboard/.zaip-managed.json +28 -28
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{DashboardHelpDialog-B4XMYP00.js → DashboardHelpDialog-C-J7yI0E.js} +3 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{PricingSettingsDialog-DvMV9yit.js → PricingSettingsDialog-6Lx9UnYo.js} +1 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{ProjectSettingsPage-CFhFcZjW.js → ProjectSettingsPage-B6Dvz-Je.js} +1 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{TraceabilityWorkspace-DkaJNHuG.js → TraceabilityWorkspace-YRJB7Gxh.js} +1 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{dashboard-localization-CwQfHYWq.js → dashboard-localization-CCXDvXwr.js} +2 -0
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{index-DB2s40tU.js → index-CYc50ABs.js} +2 -2
- package/templates/.agents/dashboard/apps/frontend/dist/index.html +1 -1
- package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
- package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
- package/templates/.agents/dashboard/modules/operations/package.json +1 -1
- package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
- package/templates/.agents/dashboard/packages/branding/package.json +1 -1
- package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
- package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +16 -16
- package/templates/.agents/dashboard/packages/local-runtime/package.json +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/server.mjs +21 -21
- package/templates/.agents/dashboard/packages/ui/package.json +1 -1
- package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
- package/templates/.agents/design/.zaip-managed.json +3 -3
- package/templates/.agents/design/apps/catalog/package.json +1 -1
- package/templates/.agents/design/packages/local-runtime/package.json +1 -1
- package/templates/.agents/requirements/autonomous-assurance.md +1 -1
- package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
- package/templates/.agents/requirements/comparative-audit.md +1 -1
- package/templates/.agents/requirements/context-engine.md +1 -1
- package/templates/.agents/requirements/cost-observability.md +1 -1
- package/templates/.agents/requirements/dashboard-launch.md +1 -1
- package/templates/.agents/requirements/data-export.md +1 -1
- package/templates/.agents/requirements/design-system.md +1 -1
- package/templates/.agents/requirements/execution-engine.md +1 -1
- package/templates/.agents/requirements/kanban-dashboard.md +1 -1
- package/templates/.agents/requirements/model-orchestration.md +1 -1
- package/templates/.agents/requirements/public-distribution.md +1 -1
- package/templates/.agents/requirements/software-architecture.md +1 -1
- package/templates/.agents/requirements/strategic-improvements.md +1 -1
- package/templates/.agents/requirements/work-lifecycle.md +1 -1
- package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
- package/templates/.agents/runtime/VERSION +1 -1
- package/templates/.agents/runtime/bin/zaip.mjs +45 -45
- package/templates/.agents/runtime/checksums.sha256 +5 -5
- package/templates/.agents/runtime/manifest.json +1 -1
- package/templates/.agents/runtime/provenance.json +4 -4
- package/templates/.agents/runtime/sbom.cdx.json +1 -1
- package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-contract.mjs +15 -5
- package/templates/.agents/skills/zaip-skill-github-deploy/scripts/deploy-publication-intent.test.mjs +33 -0
- package/templates/.agents/skills/zaip-skill-lifecycle-closure/references/post-publication-task-first.md +2 -0
- package/templates/.agents/skills/zaip-skill-task/references/commit-policy.md +1 -1
- package/templates/.agents/zaip-aios/VERSION +1 -1
- package/templates/template-manifest.json +65 -65
|
@@ -344,11 +344,11 @@ ${i}
|
|
|
344
344
|
|
|
345
345
|
## Resultado
|
|
346
346
|
|
|
347
|
-
${n}`}function Gc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Kc(e,t,n){let i=new Set;for(let r of e)i.has(r)&&n.addIssue({code:"custom",path:[t],message:`Duplicate value: ${r}`}),i.add(r)}var lP=O(()=>{"use strict"});var uP=O(()=>{"use strict"});function Xv(e,t,n,i,r,o=!1){let a=["completed","failed","cancelled"].includes(t);return{...e,revision:e.revision+1,status:t,attempt_count:t==="executing"&&e.status!=="verifying"&&!o?(e.attempt_count??0)+1:e.attempt_count,status_reason:["blocked","failed","cancelled"].includes(t)?r??n?.summary??`Task moved to ${t}.`:null,updated_at:i,started_at:t==="executing"&&e.started_at===null?i:e.started_at,finished_at:a?i:null,result:a?n:null}}function dP(e,t){return e===`Orchestrator stopped without a persisted Gui finalization decision; lifecycle was fail-closed as blocked. (Run ${t}).`||e===`Finalization barrier missing; resume after a completed zaip-agent-finalizer Sub-Run with authoritative metadata (Run ${t}).`||e===`Finalization barrier evidence_missing; resume after passed typed Evidence linked to the same Task, Change, Execution, and Run (Run ${t}).`||e.startsWith(`Completion gates did not close Run ${t}:`)}function D5(e){return e.plan_ref?.execution_id??e.prepared_plan?.execution_id??null}function _P(e,t){if(e.status!=="blocked"||e.status_reason!==t.reason||D5(e)!==t.executionId||!dP(t.reason,t.runId))throw new Error(`Task ${e.id} is not recoverable from its own completion gate`)}var pP,Yv=O(()=>{"use strict";pP={draft:["planned","blocked","failed","cancelled"],planned:["executing","blocked","failed","cancelled"],executing:["verifying","failed","blocked","cancelled"],verifying:["executing","completed","failed","blocked","cancelled"],blocked:["executing","cancelled"],completed:[],failed:["executing"],cancelled:[]}});var at,Pp,j5,mP,U5,F5,z5,_o,ts,fP=O(()=>{"use strict";qe();Ko();at=Me(Ue(),1);Hv();Gv();Gv();lP();uP();Yv();Pp=at.z.string().datetime({offset:!0}),j5=at.z.string().regex(/^[a-f0-9]{64}$/),mP=at.z.string().startsWith("TASK-"),U5=at.z.string().startsWith("CHG-"),F5=at.z.string().startsWith("REQ-"),z5=at.z.string().startsWith("AC-"),_o=at.z.object({schema_version:at.z.literal(2),id:mP,revision:at.z.number().int().positive(),change_id:U5,title:at.z.string().min(1),short_name:at.z.string().min(1),objective:at.z.string().min(1),target_release:at.z.string().regex(/^[1-9]\d*\.(?:0|[1-9]\d*)$/).nullable().optional(),status:at.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),status_reason:at.z.string().min(1).nullable().optional(),attempt_count:at.z.number().int().nonnegative().optional(),risk:at.z.enum(["lite","standard","critical"]),priority:at.z.enum(["low","medium","high","urgent"]),owner:at.z.string().min(1).nullable(),requirement_ids:at.z.array(F5).min(1),acceptance_ids:at.z.array(z5).min(1),depends_on:at.z.array(mP),write_scopes:at.z.array(at.z.string().min(1)),runtime:rd.optional(),model_profile:yo.optional(),assurance_risk_signals:Np.optional(),assurance_risk_signals_source:at.z.enum(["explicit","risk_default"]).optional(),plan_revision:at.z.number().int().positive().nullable(),plan_hash:j5.nullable(),prepared_plan:Ri.optional(),plan_ref:Ka.optional(),created_at:Pp,updated_at:Pp,started_at:Pp.nullable(),finished_at:Pp.nullable(),result:Jv.nullable()}).strict().superRefine((e,t)=>{let n=e.plan_revision===null&&e.plan_hash===null;e.status==="draft"||n&&["blocked","failed","cancelled"].includes(e.status)?(!n||e.prepared_plan!==void 0||e.plan_ref!==void 0)&&t.addIssue({code:"custom",message:`${e.status} Task without materialization cannot contain a prepared plan`}):(e.plan_revision===null||e.plan_hash===null)&&t.addIssue({code:"custom",message:`${e.status} Task requires plan_revision and plan_hash`}),e.prepared_plan!==void 0&&e.plan_ref!==void 0&&t.addIssue({code:"custom",message:"Task cannot contain prepared_plan and plan_ref"}),e.plan_ref!==void 0&&e.plan_ref.hash!==e.plan_hash&&t.addIssue({code:"custom",path:["plan_ref"],message:"plan_ref must match plan_hash"}),e.prepared_plan!==void 0&&(e.prepared_plan.source.type!=="task"||e.prepared_plan.source.task_id!==e.id||e.prepared_plan.hash!==e.plan_hash)&&t.addIssue({code:"custom",path:["prepared_plan"],message:"prepared_plan must belong to the Task and match plan_hash"}),["completed","failed","cancelled"].includes(e.status)&&(e.finished_at===null||e.result===null)&&t.addIssue({code:"custom",message:"terminal Task requires finished_at and result"}),["executing","verifying","completed"].includes(e.status)&&e.started_at===null&&t.addIssue({code:"custom",message:`${e.status} Task requires started_at`}),e.status==="completed"&&(e.result?.completed_run_id===null||e.result?.evidence_ids.length===0)&&t.addIssue({code:"custom",path:["result"],message:"completed Task requires completed_run_id and at least one Evidence"}),Kc(e.requirement_ids,"requirement_ids",t),Kc(e.acceptance_ids,"acceptance_ids",t),Kc(e.depends_on,"depends_on",t),Kc(e.write_scopes,"write_scopes",t)}),ts=class{constructor(t,n){this.filesystem=t;this.layout=n;if(n.version===1)throw new TypeError("TaskV2Repository requires a modern WorkspaceLayout")}filesystem;layout;async read(t){let n=await Ro(this.filesystem,this.layout,"task",t);if(n===null)throw new Error(`task not found: ${t}`);let i=qt(await this.filesystem.readText(n),_o);return{task:i.metadata,body:i.body}}async list(){let t=await this.filesystem.listFiles(this.layout.entityRoot("task"),".md");return Promise.all(t.map(async n=>qt(await this.filesystem.readText(n),_o).metadata))}async createDraft(t){if(t.modelProfile&&t.modelProfile.risk!==t.risk)throw new Error("Task model profile risk differs from Task risk");let i=(t.clock??new rt).now().toISOString(),r=_o.parse({schema_version:2,id:t.id,revision:1,change_id:t.changeId,title:t.title,short_name:t.shortName,objective:t.objective,target_release:t.targetRelease??null,status:"draft",attempt_count:0,risk:t.risk,...t.modelProfile===void 0?{}:{model_profile:t.modelProfile},priority:t.priority,owner:t.owner??null,requirement_ids:[...t.requirementIds],acceptance_ids:[...t.acceptanceIds],depends_on:[...t.dependsOn??[]],write_scopes:[...t.writeScopes??[]],plan_revision:null,plan_hash:null,created_at:i,updated_at:i,started_at:null,finished_at:null,result:null,assurance_risk_signals:cP(t.risk,t.assuranceRiskSignals),assurance_risk_signals_source:t.assuranceRiskSignals===void 0?"risk_default":"explicit"});return await this.filesystem.writeTextExclusive(this.path(r.id),this.serialize(r)),r}async setPreparedPlan(t,n){let i=Ri.parse(n);if(i.source.type!=="task"||i.source.task_id!==t)throw new TypeError(`Prepared plan source must be task ${t}`);let r=await this.read(t);if(r.task.status==="planned"&&r.task.prepared_plan?.hash===i.hash)return r.task;if(r.task.status!=="draft")throw new Error(`Task ${t} must be draft before prepare`);let o=i.blueprints.tasks.find(c=>c.id===t);if(o===void 0)throw new Error(`Prepared plan does not contain Task ${t}`);let a=[o.change_id===r.task.change_id?null:"change_id",o.title===r.task.title?null:"title",o.short_name===r.task.short_name?null:"short_name",o.objective===r.task.objective?null:"objective",o.risk===r.task.risk?null:"risk",o.priority===r.task.priority?null:"priority",o.owner===r.task.owner?null:"owner",Gc(o.requirement_ids,r.task.requirement_ids)?null:"requirement_ids",Gc(o.acceptance_ids,r.task.acceptance_ids)?null:"acceptance_ids",Gc(o.write_scopes,r.task.write_scopes)?null:"write_scopes"].filter(c=>c!==null),s=i.dag.nodes.find(c=>c.task_id===t);if((s===void 0||!Gc(s.depends_on,r.task.depends_on))&&a.push("depends_on"),a.length>0)throw new Error(`Prepared plan diverges from Task draft: ${a.join(", ")}`);let l=_o.parse({...r.task,revision:r.task.revision+1,status:"planned",plan_revision:i.revision,plan_hash:i.hash,prepared_plan:i,...o.model_profile===void 0?{}:{model_profile:o.model_profile},updated_at:i.prepared_at});return await this.write(l),l}async write(t,n=Kv(t)){await this.filesystem.writeTextAtomic(this.path(t.id),this.serialize(t,n))}async normalizePreparedPlan(t,n){let i=await this.read(t);if(i.task.plan_ref?.hash===n.hash)return i.task;if(i.task.prepared_plan?.hash!==n.hash)throw new Error(`Task ${t} does not contain PreparedPlan ${n.hash}`);let{prepared_plan:r,...o}=i.task,a=_o.parse({...o,revision:i.task.revision+1,plan_ref:Lc(n),updated_at:new Date().toISOString()});return await this.write(a),a}async normalizeBody(t){let n=await this.read(t);return await this.write(n.task),n.task}serialize(t,n=Kv(t)){return fn({metadata:_o.parse(t),body:n})}async transition(t,n,i=null,r=new rt,o=null){let a=await this.read(t);if(!pP[a.task.status].includes(n))throw new Error(`Invalid Task transition: ${a.task.status} -> ${n}`);let s=_o.parse(Xv(a.task,n,i,r.now().toISOString(),o));return await this.write(s),s}async recoverOwnCompletionGateBlock(t,n,i=new rt){let r=await this.read(t);_P(r.task,n);let o=_o.parse(Xv(r.task,"executing",null,i.now().toISOString(),null,!0));return await this.write(o),o}path(t){return this.layout.activePath("task",t)}}});var wt,Qv,Rge,eb=O(()=>{"use strict";qe();wt=Me(Ue(),1);Iv();qc();Vc();I0();oP();sP();fP();Hv();Yv();Qv=wt.z.string().datetime({offset:!0}),Rge=wt.z.object({id:wt.z.string().startsWith("TASK-"),title:wt.z.string().min(1),short_name:wt.z.string().min(1),status:wt.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),risk:wt.z.enum(["lite","standard","critical"]),priority:wt.z.enum(["low","medium","high","urgent"]),owner:wt.z.string().min(1).nullable().default(null),progress:wt.z.number().int().min(0).max(100),spec:wt.z.string().startsWith("SPEC-"),change:wt.z.string().startsWith("CHG-"),requirements:wt.z.array(wt.z.string().startsWith("REQ-")),depends_on:wt.z.array(wt.z.string().startsWith("TASK-")),human_decisions:wt.z.array(wt.z.string().startsWith("DEC-HUMAN-")),agent_decisions:wt.z.array(wt.z.string().startsWith("DEC-AI-")),created_at:Qv,started_at:Qv.nullable(),finished_at:Qv.nullable()}).strict()});function $p(e){return new Set(e.filter(t=>t.status!=="planned").flatMap(t=>t.dag.nodes.map(n=>n.task_id)))}var tb=O(()=>{"use strict"});function gP(e){let t=new Map,n=(i,r)=>i===null&&r===null?null:(i??0)+(r??0);for(let i of e){if(i.task_id===null)continue;let r=t.get(i.task_id)??{duration_ms:null,tokens:null,cost_brl:null};t.set(i.task_id,{duration_ms:n(r.duration_ms,i.phase==="execution"&&i.parent_run_id==null?i.duration_ms:null),tokens:n(r.tokens,i.usage.total.tokens.total),cost_brl:n(r.cost_brl,i.usage.total.cost.brl)})}return t}function Xc(e,t){let n=e.filter(a=>a.status==="completed").length,i=t.filter(a=>a.status!=="running"),r=i.filter(a=>a.status==="completed").length,o=t.filter(a=>a.work_type==="rework").length;return{completed_tasks:n,task_completion_rate:e.length===0?0:n/e.length,terminal_runs:i.length,successful_runs:r,terminal_success_rate:i.length===0?0:r/i.length,rework_rate:t.length===0?0:o/t.length}}var nb=O(()=>{"use strict"});function Lp(e){let t=e?.source_started_at??null,n=e?.source_finished_at??e?.source_occurred_at??null;return{source_started_at:t,source_finished_at:n,source_duration_ms:t===null||n===null?null:Math.max(0,Date.parse(n)-Date.parse(t)),capture_lag_ms:n===null||e===void 0?null:Math.max(0,Date.parse(e.occurred_at)-Date.parse(n))}}function Mp(e,t,n,i){let r=Date.parse(e),o=c=>{let u=c==null?Number.NaN:Date.parse(c);return Number.isFinite(u)?u:null},a=(c,u)=>{let d=o(c),_=o(u);return d!==null&&_!==null&&_>=d&&_>=r},s=[];for(let c of[...n,...i]){let u=c.source_started_at,d=c.source_finished_at;if(u!==void 0&&d!==void 0&&a(u,d)){s.push({...c,source_finished_at:d});continue}c.activity_kind==="retrospective_local_reconciliation"&&typeof c.source_occurred_at=="string"&&(o(c.source_occurred_at)??Number.NEGATIVE_INFINITY)>=r&&s.push({...c,source_started_at:e,source_finished_at:c.source_occurred_at})}s.sort((c,u)=>Date.parse(c.occurred_at)-Date.parse(u.occurred_at));let l=s.at(-1);return Lp(l===void 0?void 0:{occurred_at:l.occurred_at,source_occurred_at:l.source_occurred_at??void 0,source_started_at:l.source_started_at,source_finished_at:l.source_finished_at})}function hP(e){function t(n,i){let r=new Set([...i===null?[]:e.prds.filter(c=>c.id===i).map(c=>c.creation_run_id),...e.specs.filter(c=>n.has(c.id)).map(c=>c.creation_run_id)].filter(c=>c!=null)),o=new Set(e.changes.filter(c=>i!==null&&c.source.type==="prd"&&c.source.prd_id===i||(c.source.type==="spec"||c.source.type==="prd")&&c.source.spec_id!==null&&c.source.spec_id!==void 0&&n.has(c.source.spec_id)).map(c=>c.id)),a=new Set(e.tasks.filter(c=>o.has(c.change_id)).map(c=>c.id)),s=new Set(e.executions.filter(c=>i!==null&&c.origin.type==="prd"&&c.origin.prd_id===i||c.origin.type==="spec"&&c.origin.spec_id!==void 0&&n.has(c.origin.spec_id)||c.dag.nodes.some(u=>a.has(u.task_id))).map(c=>c.id)),l=e.runs.filter(c=>{let u=c.fold.run.spec_id!==null&&n.has(c.fold.run.spec_id)||c.fold.run.task_id!==null&&a.has(c.fold.run.task_id)||r.has(c.fold.run.run_id);return i===null?u:u||c.fold.run.prd_id===i||c.fold.run.execution_id!==null&&s.has(c.fold.run.execution_id)});return{changeIds:o,taskIds:a,executionIds:s,runs:l}}return{forSpec:n=>t(new Set([n]),null),forPrd:n=>t(new Set(e.specs.filter(i=>i.prd_id===n).map(i=>i.id)),n)}}var rb=O(()=>{"use strict"});function yP(e){let t=OC(e.map(n=>n.cost));return{conversation:ns(t.conversation),planning:ns(t.planning),execution:ns(t.execution),total:ns(t.total),new_work:ns(t.work_types.new),rework:ns(t.work_types.rework)}}function ns(e){return{events:e.usage_event_count,tokens:e.tokens,cost:e.cost,coverage:e.coverage}}function jp(e){return{human:e.filter(t=>t.origin==="human").length,agent:e.filter(t=>t.origin==="agent").length}}function Up(e,t){let n=[e.conversation,e.planning,e.execution],i=Object.values(t).map(r=>r.total);return{phase_tokens_match_total:Dp(n.map(r=>r.tokens.total),e.total.tokens.total),phase_usd_match_total:Dp(n.map(r=>r.cost.usd),e.total.cost.usd),phase_brl_match_total:Dp(n.map(r=>r.cost.brl),e.total.cost.brl),origin_tokens_match_total:Dp(i.map(r=>r.tokens.total),e.total.tokens.total)}}function Dp(e,t){let n=e.filter(i=>i!==null);return t===null?n.length===0:Math.abs(n.reduce((i,r)=>i+r,0)-t)<1e-9}function Fp(e){return e==="completed"?100:e==="verifying"?80:e==="executing"?50:["blocked","failed","cancelled"].includes(e)?0:10}function vP(e){return e==="planned"?"planning":["running","paused","verifying"].includes(e)?"executing":e}function bP(e,t){if(e==="delivered")return"completed";if(e==="blocked")return"blocked";if(e==="failed")return"failed";if(e==="cancelled")return"cancelled";let n=t.flatMap(i=>i===void 0?[]:[i.status]);return n.some(i=>["running","paused"].includes(i))?"executing":n.includes("verifying")?"verifying":n.length>0&&n.every(i=>i==="completed")?e==="active"?"verifying":"completed":e==="active"?"executing":n.includes("blocked")?"blocked":n.includes("failed")?"failed":(n.includes("planned")||["draft","ready"].includes(e),"planning")}function Yc(e){return e.filter(t=>t!==null).map(t=>new Date(t).toISOString()).sort().at(-1)??null}var Qc=O(()=>{"use strict";zn()});function SP(e){let t=e.fold.finished?.occurred_at??null,n=e.fold.effective_usage_records.findLast(l=>l.runtime)?.runtime,i=e.fold.effective_usage_records.at(-1),r=Mp(e.fold.run.occurred_at,t,e.fold.effective_usage_records,e.fold.records),o=e.fold.finished,a=typeof r.source_duration_ms=="number"&&r.source_duration_ms>=0?r.source_duration_ms:typeof o?.duration_ms=="number"&&o.duration_ms>=0&&(o.duration_provenance==="observed"||o.duration_provenance==="reconciled"||o.duration_provenance==="legacy_inferred")?o.duration_ms:null,s=typeof r.source_duration_ms=="number"&&r.source_duration_ms>=0?"observed":a===null?"unavailable":o?.duration_provenance??"unavailable";return{id:e.fold.run.run_id,artifact_path:e.artifactPath,status:e.fold.status,phase:e.fold.records.findLast(l=>"phase"in l)?.phase??e.fold.run.phase,entrypoint:e.fold.run.entrypoint,work_type:e.fold.run.work_type,run_role:G_(e.fold.run),run_kind:Py(e.fold.run),run_purpose:$y(e.fold.run),requires_finalizer:Ly(e.fold.run),parent_run_id:e.fold.run.parent_run_id,client:e.fold.run.client,agent:e.fold.run.agent,agent_name:q5(e.fold.run.agent,e.fold.run.agent_name),provider:i?.provider??e.fold.run.provider,model:e.fold.run.model,reasoning_effort:e.fold.run.reasoning_effort??null,...V5(e.fold),...W5(e.fold),service_tier:n?.service_tier??null,conversation_id:e.fold.run.conversation_id,execution_id:e.fold.run.execution_id,task_id:e.fold.run.task_id,spec_id:e.fold.run.spec_id,prd_id:e.fold.run.prd_id,change_id:e.fold.run.change_id,started_at:e.fold.run.occurred_at,finished_at:t,duration_ms:a,duration_started_at:a===null?null:o?.started_at??e.fold.run.occurred_at,duration_provenance:s,...r,pricing_segments:e.fold.effective_usage_records.map(l=>({phase:l.phase,provider:l.provider,model:l.model,service_tier:l.runtime?.service_tier??n?.service_tier??null,input_tokens:l.tokens.input,cached_input_tokens:l.tokens.cached_input,output_tokens:l.tokens.output,reasoning_tokens:l.tokens.reasoning,total_tokens:l.tokens.total,recorded_usd:l.cost.usd,recorded_brl:l.cost.brl,recorded_fx_rate:l.cost.fx_rate??null})),usage:yP([e])}}function q5(e,t){if(e==="codex")return"codex";let n=t??e;return n.startsWith("agent-")?`zaip-agent-${n.slice(6)}`:n}function V5(e){let t=new Set([...e.provider_invocation_records.map(i=>i.effective.model),...e.effective_usage_records.map(i=>i.model)].filter(i=>i!==null)),n=new Set([...e.provider_invocation_records.map(i=>i.effective.reasoning_effort),...e.effective_usage_records.map(i=>i.runtime?.reasoning_effort??null)].filter(i=>i!==null));return{effective_model:t.size===1?[...t][0]??null:null,effective_reasoning_effort:n.size===1?[...n][0]??null:null,effective_config_mixed:t.size>1||n.size>1}}function W5(e){let t=new Set([...e.model_selection_records.map(n=>n.invocation_id),...e.provider_invocation_records.map(n=>n.invocation_id)]);return t.size===0?{call_count:null,terminal_call_count:null,failed_call_count:null,cancelled_call_count:null}:{call_count:t.size,terminal_call_count:e.provider_invocation_records.length,failed_call_count:e.provider_invocation_records.filter(n=>n.status==="failed").length,cancelled_call_count:e.provider_invocation_records.filter(n=>n.status==="cancelled").length}}function kP(e,t){return e!==null&&e>=0?e:null}var ib=O(()=>{"use strict";xc();rb();Qc()});function oi(e){return e.map(t=>typeof t.source_duration_ms=="number"&&t.source_duration_ms>=0?{...t,duration_ms:t.source_duration_ms,duration_provenance:"observed",estimation_basis:null}:typeof t.duration_ms=="number"&&t.duration_ms>=0&&(t.duration_provenance==="observed"||t.duration_provenance==="reconciled"||t.duration_provenance==="legacy_inferred")?{...t,estimation_basis:null}:{...t,duration_ms:null,duration_provenance:"unavailable",estimation_basis:null})}var zp=O(()=>{"use strict"});function EP(e,t){let n=new Set(e.dag.nodes.map(_=>_.task_id)),i=new Map(t.changes.map(_=>[_.id,_])),r=new Map(t.specs.map(_=>[_.id,_])),o=new Set,a=new Set,s=_=>{o.add(_);let p=r.get(_),g=p?.prd_id??p?.parent_id??null;g!==null&&a.add(g)};e.origin.type==="spec"&&s(e.origin.spec_id),e.origin.type==="prd"&&a.add(e.origin.prd_id);for(let _ of t.tasks){if(!n.has(_.id))continue;let p=i.get(_.change_id)?.source;p&&((p.type==="spec"||p.type==="prd")&&p.spec_id&&s(p.spec_id),p.type==="prd"&&p.prd_id&&a.add(p.prd_id))}let l=t.runs.filter(_=>_.execution_id===e.id||_.task_id!==null&&n.has(_.task_id)),c=l.flatMap(_=>_.call_count===null?[]:[_.call_count]),u=l.filter(_=>_.run_purpose==="finalization"||_.agent==="agent-finalizer"||_.agent==="agent-task-finalizer"),d=new Set(u.flatMap(_=>_.status==="completed"&&_.task_id!==null?[_.task_id]:[]));return{agent_call_count:l.length,orchestrator_run_count:l.filter(_=>_.parent_run_id===null).length,subagent_run_count:l.filter(_=>_.parent_run_id!==null).length,finalizer_run_count:u.length,finalized_task_count:d.size,llm_call_count:c.reduce((_,p)=>_+p,0),llm_call_count_complete:c.length===l.length,task_count:n.size,spec_count:o.size,prd_count:a.size,duration_ms:B5(l.filter(_=>_.parent_run_id===null)),total_tokens:wP(l.map(_=>_.usage?.tokens.total??null)),cost_brl:wP(l.map(_=>_.usage?.cost.brl??null))}}function wP(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function B5(e){let t=e.flatMap(n=>typeof n.source_duration_ms=="number"&&n.source_duration_ms>=0?[n.source_duration_ms]:typeof n.duration_ms=="number"&&n.duration_ms>=0&&(n.duration_provenance==="observed"||n.duration_provenance==="reconciled"||n.duration_provenance==="legacy_inferred")?[n.duration_ms]:[]);return t.length===0?null:t.reduce((n,i)=>n+i,0)}var AP=O(()=>{"use strict"});function qp(e){let t=TP(e.from??null,"from"),n=TP(e.to??null,"to");if(t!==null&&n!==null&&t>n)throw new Error("from must not be after to");return{from:t,to:n}}function TP(e,t){if(e===null||e.length===0)return null;let n=/^\d{4}-\d{2}-\d{2}$/.test(e)?t==="to"?`${e}T23:59:59.999-03:00`:`${e}T00:00:00.000-03:00`:e,i=Date.parse(n);if(Number.isNaN(i))throw new Error(`${t} must be an ISO timestamp`);return new Date(i).toISOString()}var ob=O(()=>{"use strict"});function Mn(e){let t=n=>{let i=e.map(n),r=o=>{let a=o.filter(s=>s!==null);return a.length===0?null:a.reduce((s,l)=>s+l,0)};return{events:i.reduce((o,a)=>o+a.events,0),tokens:{input:r(i.map(o=>o.tokens.input)),cached_input:r(i.map(o=>o.tokens.cached_input)),output:r(i.map(o=>o.tokens.output)),reasoning:r(i.map(o=>o.tokens.reasoning)),total:r(i.map(o=>o.tokens.total))},cost:{usd:r(i.map(o=>o.cost.usd)),brl:r(i.map(o=>o.cost.brl))},coverage:{events:i.reduce((o,a)=>o+a.coverage.events,0),tokens:i.reduce((o,a)=>o+a.coverage.tokens,0),usd:i.reduce((o,a)=>o+a.coverage.usd,0),brl:i.reduce((o,a)=>o+a.coverage.brl,0)}}};return{conversation:t(n=>n.usage.conversation),planning:t(n=>n.usage.planning),execution:t(n=>n.usage.execution),total:t(n=>n.usage.total),new_work:t(n=>n.usage.new_work),rework:t(n=>n.usage.rework)}}function Vp(e){let t=oi(e.runs),n=wc(t),i=Mn(t),r={conversation:Mn(t.filter(o=>o.entrypoint==="conversation")),task:Mn(t.filter(o=>o.entrypoint==="task")),spec:Mn(t.filter(o=>o.entrypoint==="spec")),prd:Mn(t.filter(o=>o.entrypoint==="prd"))};return{...e,runs:t,origins:r,summary:{...e.summary,run_count:t.length,execution_duration_ms:xi(n)??0,execution_day_count:new Set(n.map(o=>o.started_at.slice(0,10))).size,source_latest_at:Yc([e.summary.source_latest_at,...t.map(o=>o.finished_at??o.started_at)]),quality:Xc(e.tasks,t),reconciliation:Up(i,r),usage:i}}}function sb(e){let t=[...e.taskIds].flatMap(r=>{let o=e.tasks.get(r);return o===void 0?[]:[o]}),n=e.decisions.filter(r=>r.scope_type==="change"&&e.changeIds.has(r.scope_id)||r.scope_type==="execution"&&e.executionIds.has(r.scope_id)),i=cb(e.runs);return{id:e.id,title:e.title,created_at:e.createdAt,updated_at:e.updatedAt,kind:e.kind,parent_id:e.parentId,artifact_path:e.artifactPath,lifecycle_status:e.lifecycleStatus,work_status:bP(e.lifecycleStatus,[...e.executionIds].map(r=>e.executions.get(r))),execution_ids:[...e.executionIds].sort(),task_ids:[...e.taskIds].sort(),planned_tasks:[...e.plannedTasks],canonical_run_ids:i.canonicalRuns.map(r=>r.id).sort(),run_ids:i.canonicalRuns.map(r=>r.id).sort(),root_execution_run_ids:i.rootExecutionRuns.map(r=>r.id).sort(),execution_count:e.executionIds.size,task_count:Math.max(e.taskIds.size,e.plannedTasks.length),run_count:i.canonicalRuns.length,duration_ms:i.observedRootDuration,observed_root_duration_ms:i.observedRootDuration,observed_lifecycle_duration_ms:i.observedLifecycleDuration,duration_coverage:{eligible_runs:i.rootExecutionRuns.length,known_runs:i.knownRootRuns.length,unknown_runs:i.rootExecutionRuns.length-i.knownRootRuns.length,coverage_ratio:i.rootExecutionRuns.length===0?1:i.knownRootRuns.length/i.rootExecutionRuns.length},duration_provenance:i.observedRootDuration===null?"unavailable":"observed",lifecycle_duration_coverage:i.lifecycleCoverage,lifecycle_duration_provenance:i.observedLifecycleDuration===null?"unavailable":"observed",decisions:jp(n),rework_run_count:i.canonicalRuns.filter(r=>r.work_type==="rework").length,quality:Xc(t,i.canonicalRuns),usage:Mn(i.canonicalRuns)}}function cb(e){let t=[...new Map(e.map(a=>[a.id,a])).values()],n=t.filter(a=>a.phase==="execution"&&a.parent_run_id==null),i=n.filter(a=>ab(a)!==null),r=t.filter(a=>a.parent_run_id==null),o=r.filter(a=>ab(a)!==null);return{canonicalRuns:t,rootExecutionRuns:n,knownRootRuns:i,observedRootDuration:xi(n),observedLifecycleDuration:Z5(r),lifecycleCoverage:{eligible_runs:r.length,known_runs:o.length,unknown_runs:r.length-o.length,coverage_ratio:r.length===0?1:o.length/r.length}}}function Z5(e){let t=e.flatMap(a=>{let s=ab(a),l=Date.parse(a.source_started_at??a.duration_started_at??a.started_at);return s!==null&&Number.isFinite(l)?[{start:l,end:l+s}]:[]}).toSorted((a,s)=>a.start-s.start),n=t[0];if(n===void 0)return null;let i=0,r=n.start,o=n.end;for(let a of t.slice(1))a.start<=o?o=Math.max(o,a.end):(i+=o-r,r=a.start,o=a.end);return i+o-r}function ab(e){return typeof e.source_duration_ms=="number"&&e.source_duration_ms>=0?e.source_duration_ms:typeof e.duration_ms=="number"&&e.duration_ms>=0&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")?e.duration_ms:null}function xP(e){function t(n,i){let r=new Set([...i===null?[]:e.prds.filter(c=>c.id===i).map(c=>c.creation_run_id),...e.specs.filter(c=>n.has(c.id)).map(c=>c.creation_run_id)].filter(c=>c!=null)),o=new Set(e.changes.filter(c=>i!==null&&c.source.type==="prd"&&c.source.prd_id===i||(c.source.type==="spec"||c.source.type==="prd")&&c.source.spec_id!==null&&c.source.spec_id!==void 0&&n.has(c.source.spec_id)).map(c=>c.id)),a=new Set(e.tasks.filter(c=>o.has(c.change_id)).map(c=>c.id)),s=new Set(e.executions.filter(c=>i!==null&&c.origin.type==="prd"&&c.origin.prd_id===i||c.origin.type==="spec"&&n.has(c.origin.spec_id)||c.dag.nodes.some(u=>a.has(u.task_id))).map(c=>c.id)),l=e.runs.filter(c=>c.spec_id!==null&&n.has(c.spec_id)||c.task_id!==null&&a.has(c.task_id)||r.has(c.id)||i!==null&&(c.prd_id===i||c.execution_id!==null&&s.has(c.execution_id)));return{changeIds:o,taskIds:a,executionIds:s,runs:l}}return{forSpec:n=>t(new Set([n]),null),forPrd:n=>t(new Set(e.specs.filter(i=>i.prd_id===n).map(i=>i.id)),n)}}var lb=O(()=>{"use strict";Ec();nb();zp();Qc()});function RP(e,t){let n=new Map(e.map(r=>[r.id,ub(r.prepared_plan)])),i=new Map(t.map(r=>{let o=ub(r.prepared_plan);if(o.length>0||r.prd_id===null)return[r.id,o];let a=e.find(s=>s.id===r.prd_id);return[r.id,a===void 0?[]:ub(a.prepared_plan,r.id)]}));return{byPrd:n,bySpec:i}}function OP(e){let t=new Map;for(let n of e){if(n.kind==="interaction")continue;let i=new Set(n.dag.nodes.map(r=>r.task_id));n.origin.type==="task"&&i.add(n.origin.task_id);for(let r of i)t.set(r,new Set([...t.get(r)??[],n.id]))}return new Map([...t].map(([n,i])=>[n,[...i].sort()]))}function ub(e,t){if(e==null||e.blueprints===void 0)return[];let n=new Map(e.blueprints.changes.map(r=>[r.id,r.source.type==="spec"||r.source.type==="prd"?r.source.spec_id??null:null])),i=new Map(e.dag.nodes.map(r=>[r.task_id,r.depends_on]));return e.blueprints.tasks.filter(r=>t===void 0||n.get(r.change_id)===t).map(r=>({id:r.id,title:r.title,objective:r.objective,depends_on:i.get(r.id)??[]}))}var CP=O(()=>{"use strict"});function NP(e){return typeof e=="number"&&e>0?Math.round(e*36e5/4e6):null}function PP(e,t){let n=e.filter(o=>(o.total_tokens??0)>0);if(n.length<7||t<n.length)return e.map(o=>IP(o));let i=n.reduce((o,a)=>o+(a.total_tokens??0),0),r=0;return e.map(o=>{if(!n.includes(o))return IP(o);let a=n.at(-1)===o?t-r:1+Math.floor((t-n.length)*(o.total_tokens??0)/i);return r+=a,{...o,duration:{known_sum:a,unknown:0,complete:!0,coverage_ratio:1}}})}function db(e,t){let n=PP(e.map(([r,o])=>({key:r,total_tokens:o.usage.total_tokens.known_sum,estimated_brl:o.usage.cost.known_sum,duration:Yo(r,o).value})),t),i=new Map(n.map(r=>[r.key,r.duration]));return Object.fromEntries(e.map(([r,o])=>[r,{...o,duration:i.get(r)??Yo(r,o).value}]))}function IP(e){if((e.total_tokens??0)<=0||e.duration.known_sum>0)return e;let t=NP(e.total_tokens);return t===null?e:{...e,duration:{known_sum:t,unknown:0,complete:!0,coverage_ratio:1}}}function el(e){let t=e.filter(i=>(i.phase===void 0||i.phase==="execution")&&i.parent_run_id==null),n=new Map;for(let i of t){let r=i.duration_started_at??i.started_at;if(!z_(r)||r===null)continue;let o=Date.parse(r),a=Wt(r,"day");if(!Number.isFinite(o)||a===null)continue;if(i.duration_ms===null||i.duration_ms<0){let l=n.get(a)??{intervals:[],known:0,unknown:0};l.unknown+=1,n.set(a,l);continue}let s=o+i.duration_ms;for(let l=o;l<=s;){let c=Wt(new Date(l).toISOString(),"day");if(c===null)break;let u=Math.min(s,J5(c)),d=n.get(c)??{intervals:[],known:0,unknown:0};if(d.intervals.push({start:l,end:u}),d.known+=1,n.set(c,d),u>=s)break;l=u}}return new Map([...n].map(([i,r])=>{let o=r.known+r.unknown;return[i,{value:{known_sum:G5(r.intervals),unknown:r.unknown,complete:r.unknown===0,coverage_ratio:o===0?1:r.known/o},population:{eligible_runs:o,known_runs:r.known,unknown_runs:r.unknown}}]}))}function Yo(e,t,n,i=!1){let r=ti[e]??0,o=e>=gn.cutoffDay?n:void 0;if(i&&r===0&&o===void 0)return H5();let a=i?o?.value:e<gn.cutoffDay?void 0:t.duration,s=a?.unknown??0,l=i?o?.population.eligible_runs??0:t.runs,c=i?o?.population.known_runs??0:t.runs-s;return{value:{known_sum:r+(a?.known_sum??0),unknown:s,complete:s===0,coverage_ratio:l===0?1:c/l},population:{eligible_runs:l,known_runs:c,unknown_runs:s}}}function H5(){return{value:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},population:{eligible_runs:0,known_runs:0,unknown_runs:0}}}function J5(e){let[t,n,i]=e.split("-").map(Number),r=new Date(Date.UTC(t,n-1,i+1)),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/Sao_Paulo",timeZoneName:"longOffset"}).formatToParts(r).find(s=>s.type==="timeZoneName")?.value??"GMT",a=/^GMT([+-])(\d{2}):(\d{2})$/.exec(o);return a===null?r.getTime():r.getTime()-(Number(a[2])*60+Number(a[3]))*6e4*(a[1]==="+"?1:-1)}function G5(e){let t=0,n=Number.NaN,i=Number.NaN;for(let r of e.toSorted((o,a)=>o.start-a.start))!Number.isFinite(n)||r.start>i?(Number.isFinite(n)&&(t+=i-n),n=r.start,i=r.end):i=Math.max(i,r.end);return Number.isFinite(n)?t+i-n:t}var _b=O(()=>{"use strict";Ma()});function K5(e,t){return(t.from===null||e>=t.from.slice(0,10))&&(t.to===null||e<=t.to.slice(0,10))}function $P(e,t){let n=d=>{let _=e.reduce((m,[,f])=>m+d(f).known_sum,0),p=e.reduce((m,[,f])=>m+d(f).unknown,0),g=e.reduce((m,[,f])=>m+f.runs,0);return{value:g===p?null:_,coverage:g===0?1:(g-p)/g}},i=e.map(([d,_])=>{let p=d<=gn.cutoffDay?ti[d]??0:0,g=d<gn.cutoffDay?void 0:_.duration;return{known_sum:p+(g?.known_sum??0),unknown:g?.unknown??0,runs:_.runs}}),r=i.reduce((d,_)=>d+_.known_sum,0),o=i.reduce((d,_)=>d+_.unknown,0),a=i.reduce((d,_)=>d+_.runs,0),s=a===o&&r===0?null:r,l={value:t.from===null&&t.to===null&&s!==null?JC(s):s,coverage:a===0?1:(a-o)/a},c=n(d=>d.usage.total_tokens),u=n(d=>d.usage.cost);return{duration_ms:l.value,tokens:c.value,cost_brl:u.value,coverage:{duration:l.coverage,tokens:c.coverage,cost:u.coverage},execution_day_count:i.filter(d=>d.known_sum>0).length}}function Wp(e,t){if(e===null)return[];let n=new Map;for(let[i,r]of Object.entries(e.days)){if(!K5(i,t))continue;let o=r.tasks.length>0?r.tasks:r.specs.length>0?r.specs:r.prds;for(let a of o){let s=n.get(a.id);if(s===void 0){n.set(a.id,structuredClone(a));continue}s.run_count+=a.run_count;for(let l of["duration","total_tokens","cost"])s.metrics[l].known_sum+=a.metrics[l].known_sum,s.metrics[l].unknown+=a.metrics[l].unknown,s.metrics[l].complete=s.metrics[l].unknown===0,s.metrics[l].coverage_ratio=s.run_count===0?1:(s.run_count-s.metrics[l].unknown)/s.run_count;(a.window_at??a.occurred_at)>(s.window_at??s.occurred_at)&&(s.status=a.status,s.risk=a.risk,a.window_at!==void 0&&(s.window_at=a.window_at))}}return[...n.values()]}function LP(e){let t={},n={};for(let i of e){let r=i.status??"unclassified",o=i.risk??"unclassified";t[r]=(t[r]??0)+1,n[o]=(n[o]??0)+1}return{total:e.length,statuses:t,risks:n}}function pb(e,t,n){let i=eQ(),r={...i,tokens:{...i.tokens,total:Qo(e.metrics.total_tokens)},cost:{...i.cost,brl:Qo(e.metrics.cost)}};return{id:e.id,title:e.title??e.id,created_at:e.occurred_at,updated_at:e.window_at??null,kind:t,parent_id:e.parent_id,artifact_path:"",lifecycle_status:e.status??"unavailable",work_status:X5(e.status),execution_ids:[],task_ids:[],planned_tasks:[],canonical_run_ids:[],run_ids:[],root_execution_run_ids:[],execution_count:0,task_count:n,run_count:e.run_count,duration_ms:Qo(e.metrics.duration),observed_root_duration_ms:Qo(e.metrics.duration),observed_lifecycle_duration_ms:null,duration_coverage:Y5(e),duration_provenance:e.metrics.duration.complete?"observed":"unavailable",lifecycle_duration_coverage:Q5(),lifecycle_duration_provenance:"unavailable",decisions:{human:0,agent:0},rework_run_count:0,quality:{completed_tasks:0,task_completion_rate:0,terminal_runs:0,successful_runs:0,terminal_success_rate:0,rework_rate:0},usage:tQ(i,r)}}function MP(e){let t=e.status,n=["completed","blocked","failed","cancelled"].includes(t??"");return{schema_version:2,id:e.id,revision:0,change_id:"",title:e.title??e.id,short_name:e.id,objective:"",status:t==="draft"||t==="planned"||t==="executing"||t==="verifying"||t==="completed"||t==="failed"||t==="blocked"||t==="cancelled"?t:"draft",attempt_count:t==="planned"||t==="draft"?0:null,risk:e.risk==="lite"||e.risk==="standard"||e.risk==="critical"?e.risk:"standard",priority:"medium",owner:null,requirement_ids:[],acceptance_ids:[],depends_on:[],write_scopes:[],created_at:e.occurred_at,updated_at:e.window_at??e.occurred_at,started_at:t==="executing"||t==="verifying"||n?e.occurred_at:null,finished_at:n?e.window_at??e.occurred_at:null,result:null,artifact_path:"",progress:n?1:0,spec_id:e.parent_id,execution_started:t==="executing"||t==="verifying"||n,execution_ids:[],execution_count:0,telemetry:{duration_ms:Qo(e.metrics.duration),tokens:Qo(e.metrics.total_tokens),cost_brl:Qo(e.metrics.cost)},test_count:0}}function DP(e){return e.map(t=>({task_id:t.id,duration_ms:t.metrics.duration.known_sum,total_tokens:t.metrics.total_tokens.known_sum,cost_brl:t.metrics.cost.known_sum,run_count:t.run_count})).sort((t,n)=>n.duration_ms-t.duration_ms||t.task_id.localeCompare(n.task_id)).slice(0,5)}function Qo(e){return e.known_sum===0&&e.unknown>0?null:e.known_sum}function X5(e){return e==="delivered"?"completed":["planning","executing","verifying","completed","blocked","failed","cancelled"].includes(e??"")?e:"planning"}function Y5(e){return{eligible_runs:e.run_count,known_runs:e.run_count-e.metrics.duration.unknown,unknown_runs:e.metrics.duration.unknown,coverage_ratio:e.metrics.duration.coverage_ratio}}function Q5(){return{eligible_runs:0,known_runs:0,unknown_runs:0,coverage_ratio:1}}function eQ(){return{events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}}}function tQ(e,t){return{conversation:e,planning:e,execution:e,total:t,new_work:e,rework:e}}var jP=O(()=>{"use strict";Ma()});function mb(e,t,n=!0){let i=[...new Map(e.map(c=>[c.id,c])).values()],r=n?i.filter(c=>Hp(c.finished_at??c.started_at,t)):i,o=r.filter(c=>c.phase==="execution"&&c.parent_run_id==null),a=fb(o,t),s=c=>{let u=c.filter(d=>d!==null);return u.length===0?null:Math.round(u.reduce((d,_)=>d+_,0)*1e9)/1e9},l=c=>c.length===0?1:c.filter(u=>u!==null).length/c.length;return{duration_ms:a===void 0||a.coverage_ratio===0?null:a.known_sum,tokens:s(r.map(c=>c.total_tokens)),cost_brl:s(r.map(c=>c.cost)),coverage:{duration:a?.coverage_ratio??1,tokens:l(r.map(c=>c.total_tokens)),cost:l(r.map(c=>c.cost))},execution_day_count:new Set(o.map(c=>Wt(c.duration_started_at??c.started_at,"day")).filter(c=>c!==null)).size}}function fb(e,t){let n=el(e),r=[...new Set([...Object.keys(ti),...n.keys()])].filter(c=>Bp(c,t)).map(c=>Yo(c,{runs:0},n.get(c),!0).value);if(r.length===0)return;let o=r.reduce((c,u)=>c+u.unknown,0),a=r.reduce((c,u)=>c+u.known_sum,0),s=[...n].filter(([c])=>Bp(c,t)).reduce((c,[,u])=>c+u.population.eligible_runs,0),l=[...n].filter(([c])=>Bp(c,t)).reduce((c,[,u])=>c+u.population.known_runs,0);return{known_sum:a,unknown:o,complete:o===0,coverage_ratio:s===0?1:l/s}}function Bp(e,t){return(t.from===null||e>=t.from.slice(0,10))&&(t.to===null||e<=t.to.slice(0,10))}async function nl(e,t,n={},i={}){if(t.version===1)throw new Error("Operations projection requires a modern WorkspaceLayout");let r=new Bt(e),o=qp(n),[a,s,l,c]=await Promise.all([r.readDailyReadModels("overview"),r.readDailyReadModels("tasks"),r.readDailyReadModels("specs"),r.readDailyReadModels("prds")]);if(a===null)throw new Error("Lifecycle daily overview is not initialized");let u=Object.entries(a.days).filter(([L])=>Bp(L,o)).map(([L,J])=>[L,J.overview]),d=$P(u,o),_={runs:u.reduce((L,[,J])=>L+J.runs,0)},p=uQ(),g={...p,tokens:{...p.tokens,total:d.tokens},cost:{...p.cost,brl:d.cost_brl}},m=d.coverage,f=db(u,d.duration_ms??0),v=Wp(s,o),S=Wp(c,o),b=Wp(l,o),h=LP(v),k=h.statuses,P=h.risks,U=new Map;for(let L of v)L.parent_id!==null&&U.set(L.parent_id,(U.get(L.parent_id)??0)+1);let $=new Map(b.map(L=>[L.id,L.parent_id])),B=S.map(L=>pb(L,"prd",v.filter(J=>J.parent_id===L.id).length+[...U].filter(([J])=>$.get(J)===L.id).reduce((J,[,le])=>J+le,0))),z=b.map(L=>pb(L,"spec",U.get(L.id)??0)),R=DP(v);return{schema_version:2,layout_version:t.version,readonly:!0,source:".agents/records",filters:o,summary:{prd_count:B.length,spec_count:z.length,execution_count:0,task_count:h.total,run_count:_.runs,overview_metrics:{duration_ms:d.duration_ms,execution_day_count:d.execution_day_count,tokens:d.tokens,cost_brl:d.cost_brl,prd_count:B.length,spec_count:z.length,selected_counts:{prds:B.length,specs:z.length},task_count:h.total,completed_prd_count:B.filter(L=>L.work_status==="completed").length,completed_spec_count:z.filter(L=>L.work_status==="completed").length,completed_task_count:k.completed??0,task_status_counts:k,task_risk_counts:P,top_tasks:R,latest_task_created_at:v.map(L=>L.occurred_at).sort().at(-1)??null,coverage:{duration:m.duration,tokens:m.tokens,cost:m.cost},data_source:"lifecycle_manifest_summary",partial:!0},decisions:{human:0,agent:0},source_latest_at:a.source_latest_at,quality:{completed_tasks:0,task_completion_rate:0,terminal_runs:0,successful_runs:0,terminal_success_rate:0,rework_rate:0},reconciliation:{phase_tokens_match_total:!1,phase_usd_match_total:!1,phase_brl_match_total:!1,origin_tokens_match_total:!1},usage:tl(p,g),periods:{daily:f}},origins:{conversation:tl(p,p),task:tl(p,p),spec:tl(p,p),prd:tl(p,p)},prds:B,specs:z,tasks:i.includeBoardTasks?v.map(MP):[],changes:[],executions:[],runs:[],decisions:[],evidences:[],validations:[]}}function nQ(e,t){return Object.fromEntries(e.map(([n,i])=>{let r=fb(t.filter(iQ),{from:n,to:n});return[n,{...i,...r===void 0?{}:{duration:r}}]}))}function rQ(e,t){let n={},i={},r=0;for(let o of e){let s=o.finished_at??(typeof o.data?.finished_at=="string"?o.data.finished_at:null)??o.updated_at;if(!Hp(s,t))continue;r+=1;let l=o.status??"unclassified",c=o.risk??"unclassified";n[l]=(n[l]??0)+1,i[c]=(i[c]??0)+1}return{total:r,statuses:n,risks:i}}function Hp(e,t){let n=new Date(e).toISOString();return(t.from===null||n>=t.from)&&(t.to===null||n<=t.to)}function UP(e,t){let n=new Map;for(let i of e){if(i.task_id===null||!t.has(i.task_id))continue;let r=n.get(i.task_id)??{task_id:i.task_id,duration_ms:0,total_tokens:0,cost_brl:0,run_count:0,runs:[]};r.runs.push(i),r.total_tokens+=i.total_tokens??0,r.cost_brl+=i.cost??0,r.run_count+=1,n.set(i.task_id,r)}return[...n.values()].map(({runs:i,...r})=>({...r,duration_ms:xi(i)??0})).sort((i,r)=>r.duration_ms-i.duration_ms||i.task_id.localeCompare(r.task_id)).slice(0,5)}function iQ(e){return e.phase==="execution"&&e.parent_run_id==null}function oQ(e,t,n){let i=t===null?null:Wt(t,"day"),r=n===null?null:Wt(n,"day");return Object.entries(aQ(e)).filter(([o])=>(i===null||o>=i)&&(r===null||o<=r))}function aQ(e){let t=[...new Map((e.run_metrics??[]).map(o=>[o.id,o])).values()],n=Object.values(e.periods.daily).reduce((o,a)=>o+a.runs,0);if(t.length===0||t.length!==n)return e.periods.daily;let i=new Map;for(let o of t){let a=Wt(o.finished_at??o.started_at,"day");a!==null&&i.set(a,[...i.get(a)??[],o])}let r=new Set([...Object.keys(e.periods.daily),...i.keys()]);return Object.fromEntries([...r].map(o=>{let a=e.periods.daily[o]??sQ(e.usage.cost.currency),s=i.get(o)??[];return[o,{...a,runs:s.length,usage:{...a.usage,total_tokens:Zp(s.map(l=>l.total_tokens)),cost:{...Zp(s.map(l=>l.cost)),currency:a.usage.cost.currency??e.usage.cost.currency}},events:Zp(s.map(l=>l.events))}]}))}function Zp(e){let t=e.filter(i=>i!==null),n=e.length-t.length;return{known_sum:t.reduce((i,r)=>i+r,0),unknown:n,complete:n===0,coverage_ratio:e.length===0?1:t.length/e.length}}function sQ(e){let t=Zp([]);return{prds:0,specs:0,tasks:0,validations:0,evidences:0,runs:0,usage:{input_tokens:t,output_tokens:t,total_tokens:t,cost:{...t,currency:e}},events:t}}function cQ(e,t,n){return UP((e.run_metrics??[]).filter(i=>Hp(i.finished_at??i.started_at,t)),n)}function lQ(e,t){return Hp(e.updated_at,t)}function uQ(){return{events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}}}function tl(e,t){return{conversation:e,planning:e,execution:e,total:t,new_work:e,rework:e}}function dQ(e){let t=n=>e.length===0?1:n/e.length;return{duration:t(e.filter(n=>n.duration_ms!==null).length),tokens:t(e.filter(n=>n.total_tokens!==null).length),cost:t(e.filter(n=>n.cost!==null).length)}}var gb=O(()=>{"use strict";ri();Ma();Ec();_b();ob();jP()});function FP(e){return[...e].sort((t,n)=>n.started_at.localeCompare(t.started_at)||n.id.localeCompare(t.id))}var zP=O(()=>{"use strict"});async function qP(e,t,n){if(t.version===1)throw new TypeError("Operations projection requires a modern layout");let i=(await Promise.all(pQ(t.entityRoot("run"),n).map(o=>e.listFiles(o,".jsonl")))).flat();return(await _Q(i,32,async o=>{let a=qa(za(await e.readText(o))),s=a.finished?.occurred_at??a.run.occurred_at;return(n.from!==null||n.to!==null)&&!mQ(s,n)?null:{fold:a,artifactPath:o,cost:{run:a.run,records:a.records,effective_usage_records:a.effective_usage_records}}})).filter(o=>o!==null).sort((o,a)=>o.fold.run.run_id.localeCompare(a.fold.run.run_id))}async function _Q(e,t,n){let i=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);i.push(...await Promise.all(o.map(n)))}return i}function pQ(e,t){return[e]}function mQ(e,t){let n=new Date(e).toISOString();return(t.from===null||n>=t.from)&&(t.to===null||n<=t.to)}var VP=O(()=>{"use strict";xc()});async function Jp(e,t,n){let i=new Map(t.map(o=>[o.id,0])),r=new Map;for(let o of t)r.set(o.change_id,[...r.get(o.change_id)??[],o]);for(let[o,a]of r){let s=n(o).replace(/\\/g,"/"),l=s.slice(0,s.lastIndexOf("/")),c;try{c=await e.listFiles(l)}catch{continue}let u=c.filter(d=>d.replace(/\\/g,"/").includes("/artifacts/tests/")&&/\.(?:md|json|jsonl|txt|log)$/i.test(d));for(let d of u){let _;try{_=await e.readText(d)}catch{continue}for(let p of a)_.includes(p.id)&&i.set(p.id,(i.get(p.id)??0)+1)}}return i}var hb=O(()=>{"use strict"});function ZP(e,t){let n=mb(e.map(i=>({id:i.id,started_at:i.started_at,finished_at:i.finished_at??null,phase:i.phase??null,parent_run_id:i.parent_run_id??null,duration_started_at:i.source_started_at??i.duration_started_at??null,duration_ms:i.source_duration_ms!==null&&i.source_duration_ms!==void 0?i.source_duration_ms:i.duration_ms,total_tokens:i.usage.total.tokens.total,cost:i.usage.total.cost.brl})),t,!1);return{duration_ms:n.duration_ms,execution_day_count:n.execution_day_count,tokens:n.tokens,cost_brl:n.cost_brl}}async function il(e,t,n={},i={}){if(t.version===1)throw new Error("Operations projection requires a modern WorkspaceLayout");let r=qp(n),o=new Bt(e),a=new Ho(e,t),s=new Jo(e,t),l=new Go(e,t),c=new lo(e,t),u=new ts(e,t),d=new J_(e,t),[_,p]=await Promise.all([o.readEntities(),i.overviewOnly?Promise.resolve([]):qP(e,t,r)]);if(_.length===0&&await o.readSummary()===null&&!await e.exists(".agents/records/lifecycle/.gitkeep"))throw new Error("Lifecycle manifest is not initialized; run `zaip manifest rebuild --confirm-full-scan`");let g=rl(_,"prd"),m=rl(_,"spec"),f=rl(_,"change"),v=rl(_,"execution"),S=rl(_,"task"),b=hQ(_),h=gQ(_),k=fQ(_),P=p.map(SP),U=g.filter(D=>BP(D.status,D.updated_at,r)),$=m.filter(D=>BP(D.status,D.updated_at,r)),B=f.filter(D=>yb(D,r)),z=v.filter(D=>yb(D,r)),R=S.filter(D=>yb(D,r)),L=b.filter(D=>rs(D.created_at,r)),J=h.filter(D=>rs(D.observed_at,r)),le=k.filter(D=>rs(D.executed_at,r)),j=P.filter(D=>rs(D.finished_at??D.started_at,r)),Q=oi(j),C=new Map(f.map(D=>[D.id,D])),F=new Map(S.map(D=>[D.id,D])),X=new Map(v.map(D=>[D.id,D])),ne=xP({changes:f,tasks:S,executions:v,prds:g,specs:m,runs:Q}),ve=i.overviewOnly||i.skipTestArtifacts?new Map:await Jp(e,R,D=>l.path(D)),ge=$p(v),q=OP(v),A=gP(Q),I=RP(g,m),he=U.map(D=>{let Ne=ne.forPrd(D.id);return sb({id:D.id,title:D.title,createdAt:D.created_at,updatedAt:D.updated_at,kind:"prd",parentId:null,artifactPath:a.path(D.id),lifecycleStatus:D.status,...Ne,decisions:b,executions:X,tasks:F,plannedTasks:I.byPrd.get(D.id)??[]})}),me=$.map(D=>{let Ne=ne.forSpec(D.id);return sb({id:D.id,title:D.title,createdAt:D.created_at,updatedAt:D.updated_at,kind:"spec",parentId:D.prd_id,artifactPath:s.path(D.id),lifecycleStatus:D.status,...Ne,decisions:b,executions:X,tasks:F,plannedTasks:I.bySpec.get(D.id)??[]})}),Le=R.map(D=>{let Ne=C.get(D.change_id);return{...D,attempt_count:D.attempt_count??null,artifact_path:u.path(D.id),progress:Fp(D.status),test_count:ve.get(D.id)??0,spec_id:Ne?.source.type==="spec"||Ne?.source.type==="prd"?Ne.source.spec_id:null,execution_started:ge.has(D.id),execution_ids:q.get(D.id)??[],execution_count:q.get(D.id)?.length??0,telemetry:A.get(D.id)??null}}),Ce=Mn(Q),Pe=wc(Q),rn=ZP(Q,r),Y=i.overviewOnly?await nl(e,t,r):null,ce=WP(R,D=>D.status),$e=WP(R,D=>D.risk),Xe=HP(U,$),x={prd_count:he.length,spec_count:me.length,selected_counts:{prds:he.length,specs:me.length},task_count:R.length,completed_prd_count:Xe.prds,completed_spec_count:Xe.specs,completed_task_count:ce.completed??0,task_status_counts:ce,task_risk_counts:$e,latest_task_created_at:Yc(R.map(D=>D.created_at))},se={conversation:Mn(Q.filter(D=>D.entrypoint==="conversation")),task:Mn(Q.filter(D=>D.entrypoint==="task")),spec:Mn(Q.filter(D=>D.entrypoint==="spec")),prd:Mn(Q.filter(D=>D.entrypoint==="prd"))};return{schema_version:2,layout_version:t.version,readonly:!0,source:".agents/records",filters:r,summary:{prd_count:he.length,spec_count:me.length,execution_count:z.length,task_count:R.length,run_count:Q.length,execution_duration_ms:xi(Pe)??0,execution_day_count:new Set(Pe.map(D=>D.started_at.slice(0,10))).size,overview_metrics:Y?.summary.overview_metrics===void 0?{...rn,...x,data_source:"run_records",partial:!1}:{...Y.summary.overview_metrics,...x,partial:!1},decisions:jp(L),source_latest_at:Y?.summary.source_latest_at??Yc([...U.map(D=>D.updated_at),...$.map(D=>D.updated_at),...B.map(D=>D.updated_at),...z.map(D=>D.updated_at),...R.map(D=>D.updated_at),...L.map(D=>D.created_at),...Q.map(D=>D.finished_at??D.started_at)]),quality:Xc(R,Q),reconciliation:Up(Ce,se),usage:Y?.summary.usage??Ce},origins:se,prds:he,specs:me,tasks:Le,changes:i.overviewOnly&&!i.includeOverviewChanges?[]:B.map(D=>({...D,artifact_path:l.path(D.id)})),executions:i.overviewOnly?[]:z.map(D=>({...D,kind:D.kind??"delivery",client_turn_id:D.client_turn_id??null,...EP(D,{runs:Q.map(Ne=>({agent:Ne.agent,call_count:Ne.call_count,duration_ms:Ne.duration_ms,...Ne.duration_provenance===void 0?{}:{duration_provenance:Ne.duration_provenance},execution_id:Ne.execution_id,finished_at:Ne.finished_at,parent_run_id:Ne.parent_run_id,run_purpose:Ne.run_purpose,source_duration_ms:Ne.source_duration_ms??null,started_at:Ne.started_at,status:Ne.status,task_id:Ne.task_id,usage:Ne.usage.total})),tasks:R,changes:B,specs:$}),artifact_path:c.path(D.id),work_status:vP(D.status)})),runs:i.overviewOnly?[]:FP(Q),evidences:J,validations:le,decisions:i.overviewOnly?[]:L.map(D=>({id:D.id,title:D.title,origin:D.origin,scope_type:D.scope_type,scope_id:D.scope_id,artifact_path:d.path(D.scope_type,D.scope_id,D.id),created_at:D.created_at}))}}function HP(e,t){return{prds:e.filter(n=>n.status==="delivered").length,specs:t.filter(n=>n.status==="delivered").length}}function WP(e,t){return e.reduce((n,i)=>{let r=t(i);return n[r]=(n[r]??0)+1,n},{})}function fQ(e){return e.flatMap(t=>{let n=t.data;return t.kind!=="validation"||n===null||typeof n.executed_at!="string"?[]:[{id:t.id,task_id:typeof n.task_id=="string"?n.task_id:null,executed_at:n.executed_at}]})}function gQ(e){return e.flatMap(t=>{let n=t.data;return t.kind!=="evidence"||n===null||typeof n.observed_at!="string"?[]:[{id:t.id,task_id:typeof n.task_id=="string"?n.task_id:null,observed_at:n.observed_at}]})}function rl(e,t){return e.flatMap(n=>n.kind===t&&n.data!==null?[{...n.data,id:n.id,title:n.title??n.data.title,status:n.status??n.data.status,risk:n.risk??n.data.risk,priority:n.priority??n.data.priority,updated_at:n.updated_at}]:[])}function hQ(e){return e.flatMap(t=>{if(t.kind!=="decision"||t.data===null)return[];let n=t.data;return n.origin!=="human"&&n.origin!=="agent"||n.scope_type!=="change"&&n.scope_type!=="execution"||typeof n.scope_id!="string"||typeof n.created_at!="string"?[]:[{id:t.id,title:t.title??t.id,origin:n.origin,scope_type:n.scope_type,scope_id:n.scope_id,created_at:n.created_at}]})}function yb(e,t){return rs(e.finished_at??e.updated_at,t)}function BP(e,t,n){return rs(t,n)}function rs(e,t){let n=new Date(e).toISOString();return(t.from===null||n>=t.from)&&(t.to===null||n<=t.to)}var JP=O(()=>{"use strict";xc();ri();Ko();eb();Ec();tb();nb();ib();zp();AP();ob();lb();CP();gb();zP();VP();hb();Qc();rb();ib();zp();lb()});async function vb(e,t,n){if(t.version===1)throw new Error("Task detail requires a modern WorkspaceLayout");let i=new ts(e,t),r=new Go(e,t),o=new lo(e,t),{task:a,body:s}=await i.read(n),{change:l}=await r.read(a.change_id),c=l.source.type==="spec"||l.source.type==="prd"?l.source.spec_id:null,u=await Jp(e,[a],g=>r.path(g)),d=await o.list(),_=$p(d),p=d.filter(g=>g.kind!=="interaction"&&(g.origin.type==="task"&&g.origin.task_id===a.id||g.dag.nodes.some(m=>m.task_id===a.id))).map(g=>g.id).sort();return{task:{...a,attempt_count:a.attempt_count??null,artifact_path:i.path(a.id),progress:Fp(a.status),spec_id:c,execution_started:_.has(a.id),execution_ids:p,execution_count:p.length,test_count:u.get(a.id)??0},body:s,artifact_path:i.path(a.id)}}async function bb(e,t,n){if(t.version===1)throw new Error("PRD detail requires a modern WorkspaceLayout");let i=new Ho(e,t),{prd:r,body:o}=await i.read(n);return{id:r.id,title:r.title,body:o,artifact_path:i.path(r.id)}}async function Sb(e,t,n){if(t.version===1)throw new Error("SPEC detail requires a modern WorkspaceLayout");let i=new Jo(e,t),{spec:r,body:o}=await i.read(n);return{id:r.id,title:r.title,body:o,artifact_path:i.path(r.id)}}var GP=O(()=>{"use strict";Ko();eb();tb();hb();Qc()});var KP={};vS(KP,{aggregateOverviewRunMetrics:()=>mb,aggregateTopTasks:()=>UP,buildOperationsProjection:()=>il,buildQuickOperationsProjection:()=>nl,coverageFromRuns:()=>dQ,createDescendantQueries:()=>hP,deliveredMacroCounts:()=>HP,effectiveOperationsDurationMs:()=>kP,estimatedTokenDurationMs:()=>NP,hybridDailyDuration:()=>Yo,hybridLegacyDurationMetric:()=>fb,latestObservedSourceTiming:()=>Mp,macroInWindow:()=>lQ,manifestDailyPeriods:()=>oQ,normalizeDailyPeriods:()=>db,normalizeTokenBackedDailyDuration:()=>PP,observedExecutionElapsedMs:()=>xi,observedMacroRunTelemetry:()=>cb,observedSourceTiming:()=>Lp,overviewMetricTotals:()=>ZP,projectExecutionDurations:()=>oi,readPrdDetail:()=>bb,readSpecDetail:()=>Sb,readTaskDetail:()=>vb,recalculateOperationsRunSummary:()=>Vp,rootExecutionDurationByDay:()=>el,summaryTopTasks:()=>cQ,taskCountsInWindow:()=>rQ,withExecutionDurations:()=>nQ});var ea=O(()=>{"use strict";Ec();JP();_b();gb();GP()});var w8={};vS(w8,{SqliteReadModelFileSystem:()=>ct,app:()=>S8,createDashboardApp:()=>yS,dashboardWorkspaceKey:()=>nm,defaultDashboardApp:()=>hS,githubRepositoryFromRemote:()=>em,manifestRun:()=>Ob,mergeManifestRuns:()=>ol,openWorkIds:()=>aC,projectAllTimeTopTasks:()=>Qp,projectionPeriodFilter:()=>Et,rebuildSqliteReadModel:()=>_l,reconciliationNeedsRefresh:()=>cM,reconciliationResult:()=>Lb,validateSqliteReadModelSchema:()=>na});module.exports=ZM(w8);var jM=require("node:crypto"),gl=require("node:path");var SS="x-hono-already-sent";var El=require("node:http"),_i=require("node:http2"),Om=require("node:stream");var kS=e=>((...t)=>{if(typeof t[0]=="function"){let[n,i]=t;return async function(o,a){let s=await n(o),l=await e(o,s,i);if(l)return l;await a()}}else{let[n,i,r]=t;return(async()=>{let o=await e(n,i,r);if(!o)throw new Error("Failed to upgrade WebSocket");return o})()}});var Kn=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},HM=/^\/[!#$&-;=?-\[\]_a-z~]*$/,JM=/\/\.\.?(?:[/?#]|$)/,GM=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,KM=(e,t,n)=>{let i=`${e}://${t}${n}`;if(GM.test(t)){if(n.length===0)return i+"/";if(n.charCodeAt(0)!==47)throw new Kn("Invalid URL");return!HM.test(n)||JM.test(n)?new URL(i).href:i}else{let r=new URL(i);if(r.hostname.length!==t.length&&r.hostname!==(t.includes(":")?t.replace(/:\d+$/,""):t).toLowerCase())throw new Kn("Invalid host header");return r.href}},XM=e=>e instanceof Kn?e:new Kn(e.message,{cause:e}),YM=global.Request,oa=class extends YM{constructor(e,t){if(typeof e=="object"&&$i in e){let n=t!==void 0&&"body"in t&&t.body!=null;if(e[pi]&&!n)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[$i]()}typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},CS=e=>{let t=[],n=e.rawHeaders;for(let i=0,r=n.length;i<r;i+=2){let o=n[i];o.charCodeAt(0)!==58&&t.push([o,n[i+1]])}return new Headers(t)},IS=Symbol("wrapBodyStream"),QM=new Set(["latin1","binary","hex","base64","base64url"]),eD=e=>e===null||QM.has(e),Rm=Symbol("bodyBufferedBeforeDisconnect"),Cm=Symbol("bodyBufferedLengthBeforeDisconnect"),NS=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),Mm=e=>!(e instanceof _i.Http2ServerRequest)&&!!e.complete&&!!e.readableAborted&&typeof e.read=="function"&&eD(e.readableEncoding),wS=e=>{if(e.readableDidRead||!Mm(e))return;let t=e;t[Cm]??=e.readableLength},bl=(e,t)=>{if(e.readableDidRead&&!t||!Mm(e))return;let n=e;if(n[Rm]!==void 0)return n[Rm];let i,r=e.errored;if(r&&r.code!=="ECONNRESET")i=r;else if(n[Cm]!==void 0&&e.readableLength!==n[Cm])i=Sl();else{let o=t??[],a=e.read();a!==null&&o.push(NS(a,e.readableEncoding));let s=o.length===1?o[0]:Buffer.concat(o);i=s;let l=e.headers["content-length"];if(typeof l=="string"&&/^\d+$/.test(l)){let c=Number(l);Number.isSafeInteger(c)&&s.length!==c&&(i=Sl())}}return n[Rm]=i,i},ES=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},tD=(e,t,n,i,r)=>{let o={method:e,headers:n,signal:r.signal};if(e==="TRACE"){o.method="GET";let a=new oa(t,o);return Object.defineProperty(a,"method",{get(){return"TRACE"}}),a}if(!(e==="GET"||e==="HEAD"))if("rawBody"in i&&i.rawBody instanceof Buffer)o.body=new ReadableStream({start(a){a.enqueue(i.rawBody),a.close()}});else if(i[IS]){let a;o.body=new ReadableStream({async pull(s){try{if(!a){let u=bl(i);if(u!==void 0){ES(s,u);return}}a||=Om.Readable.toWeb(i).getReader();let{done:l,value:c}=await a.read();l?s.close():s.enqueue(c)}catch(l){s.error(l)}}})}else{let a=bl(i);a!==void 0?o.body=new ReadableStream({start(s){ES(s,a)}}):o.body=Om.Readable.toWeb(i)}return new oa(t,o)},$i=Symbol("getRequestCache"),ui=Symbol("requestCache"),aa=Symbol("incomingKey"),fs=Symbol("urlKey"),PS=Symbol("methodKey"),$S=Symbol("headersKey"),ps=Symbol("abortControllerKey"),Im=Symbol("getAbortController"),Nm=Symbol("abortRequest"),Pi=Symbol("bodyBuffer"),vl=Symbol("bodyReadPromise"),pi=Symbol("bodyConsumedDirectly"),AS=Symbol("bodyLockReader"),ms=Symbol("abortReason"),Sl=()=>new TypeError("Body is unusable"),gs=()=>Promise.reject(Sl()),nD=new TextDecoder,rD=e=>{if(e[pi])return gs();e[pi]=!0},iD=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),oD=e=>(e[$S]||=CS(e[aa])).get("content-type")||"",aD=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,sD=e=>{if(typeof e!="string"||e.length===0)return"GET";switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return e}let t=e.toUpperCase();switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return t;default:return e}},cD=e=>{if(!aD.test(e))return new TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t==="CONNECT"||t==="TRACK"||t==="TRACE"&&e!=="TRACE")return new TypeError(`'${e}' HTTP method is unsupported.`)},Dm=(e,t,n)=>{if(e[pi])return gs();let i=e.method;if(i==="GET"||i==="HEAD")return e[$i]()[t]();let r=cD(i);if(r)return Promise.reject(r);if(e[ui]&&i!=="TRACE")return e[ui][t]();let o=rD(e);if(o)return o;let a=lD(e);if(a){let s=Promise.resolve(n(a,e));return e[Pi]=void 0,s}return uD(e).then(s=>{let l=n(s,e);return e[Pi]=void 0,l})},lD=e=>{let t=e[aa];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},TS=(e,t)=>{if(t.errored)return t.errored;let n=e[ms];return n!==void 0?n instanceof Error?n:new Error(String(n)):new Error("Client connection prematurely closed.")},uD=e=>{if(e[Pi])return Promise.resolve(e[Pi]);if(e[vl])return e[vl];let t=e[aa];if(t.readableDidRead)return gs();let n=bl(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[Pi]=n,Promise.resolve(n));let i=new Promise((r,o)=>{let a=[],s=!1,l=m=>{s||(s=!0,g(),m())},c=m=>{let f=t.errored??m;return!Mm(t)||f&&f.code!=="ECONNRESET"?!1:(l(()=>{let v=bl(t,a);v instanceof Error?o(v):v===void 0?o(m??TS(e,t)):(e[Pi]=v,r(v))}),!0)},u=m=>{a.push(NS(m,t.readableEncoding))},d=()=>{l(()=>{let m=a.length===1?a[0]:Buffer.concat(a);e[Pi]=m,r(m)})},_=m=>{c(m)||l(()=>{o(m)})},p=()=>{if(t.readableEnded){d();return}c()||l(()=>{o(TS(e,t))})},g=()=>{t.off("data",u),t.off("end",d),t.off("error",_),t.off("close",p),e[vl]=void 0};t.on("data",u),t.on("end",d),t.on("error",_),t.on("close",p),queueMicrotask(()=>{s||(t.readableEnded?d():t.errored?_(t.errored):t.destroyed&&p())})});return e[vl]=i,i},Yn={get method(){return this[PS]},get url(){return this[fs]},get headers(){return this[$S]||=CS(this[aa])},[Nm](e){this[ms]===void 0&&(this[ms]=e);let t=this[ps];t&&!t.signal.aborted&&t.abort(e)},[Im](){return this[ps]||=new AbortController,this[ms]!==void 0&&!this[ps].signal.aborted&&this[ps].abort(this[ms]),this[ps]},[$i](){let e=this[Im]();if(this[ui])return this[ui];let t=this.method;if(this[pi]&&!(t==="GET"||t==="HEAD")){this[Pi]=void 0;let n={method:t==="TRACE"?"GET":t,headers:this.headers,signal:e.signal};t!=="TRACE"&&(n.body=new ReadableStream({start(r){r.close()}}),n.duplex="half");let i=new oa(this[fs],n);return t==="TRACE"&&Object.defineProperty(i,"method",{get(){return"TRACE"}}),this[ui]=i}return this[ui]=tD(this.method,this[fs],this.headers,this[aa],e)},get body(){if(!this[pi])return this[$i]().body;let e=this[$i]();return!this[AS]&&e.body&&(this[AS]=e.body.getReader()),e.body},get bodyUsed(){return this[pi]?!0:this[ui]?this[ui].bodyUsed:!1}};Object.defineProperty(Yn,"signal",{get(){return this[Im]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(Yn,e,{get(){return this[$i]()[e]}})});["clone","formData"].forEach(e=>{Object.defineProperty(Yn,e,{value:function(){if(this[pi]){if(e==="clone")throw Sl();return gs()}return this[$i]()[e]()}})});Object.defineProperty(Yn,"text",{value:function(){return Dm(this,"text",e=>nD.decode(e))}});Object.defineProperty(Yn,"arrayBuffer",{value:function(){return Dm(this,"arrayBuffer",e=>iD(e))}});Object.defineProperty(Yn,"blob",{value:function(){return Dm(this,"blob",(e,t)=>{let n=oD(t),i=n?{headers:{"content-type":n}}:void 0;return new Response(e,i).blob()})}});Object.defineProperty(Yn,"json",{value:function(){return this[pi]?gs():this.text().then(JSON.parse)}});Object.defineProperty(Yn,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[ui]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Yn,oa.prototype);var dD=(e,t)=>{let n=Object.create(Yn);n[aa]=e,n[PS]=sD(e.method);let i=e.url||"";if(i[0]!=="/"&&(i.startsWith("http://")||i.startsWith("https://"))){if(e instanceof _i.Http2ServerRequest)throw new Kn("Absolute URL for :path is not allowed in HTTP/2");try{n[fs]=new URL(i).href}catch(a){throw new Kn("Invalid absolute URL",{cause:a})}return n}let r=(e instanceof _i.Http2ServerRequest?e.authority:e.headers.host)||t;if(!r)throw new Kn("Missing host header");let o;if(e instanceof _i.Http2ServerRequest){if(o=e.scheme,!(o==="http"||o==="https"))throw new Kn("Unsupported scheme")}else o=e.socket&&e.socket.encrypted?"https":"http";try{n[fs]=KM(o,r,i)}catch(a){throw a instanceof Kn?a:new Kn("Invalid URL",{cause:a})}return n},Ni="text/plain; charset=UTF-8",Pm=Symbol("responseCache"),ia=Symbol("getResponseCache"),di=Symbol("cache"),jm=global.Response,Xn=class LS{#e;#t;[ia](){let t=this[di],n=t&&t[2]instanceof Headers?t[2]:void 0;return delete this[di],this[Pm]||=new jm(this.#e,n?{status:this.#t?.status,statusText:this.#t?.statusText,headers:n}:this.#t)}constructor(t,n){let i;if(this.#e=t,n instanceof LS){let r=n[Pm];if(r){this.#t=r,this[ia]();return}else this.#t=n.#t,i=new Headers(n.headers)}else this.#t=n;(t==null||typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[di]=[n?.status||200,t??null,i||n?.headers])}get headers(){let t=this[di];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||(t[1]===null?void 0:{"content-type":Ni}))),t[2]):this[ia]().headers}get status(){return this[di]?.[0]??this[ia]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(Xn.prototype,e,{get(){return this[ia]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(Xn.prototype,e,{value:function(){return this[ia]()[e]()}})});Object.defineProperty(Xn.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Pm]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Xn,jm);Object.setPrototypeOf(Xn.prototype,jm.prototype);var _D=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,pD=e=>e instanceof URL?e.href:_D.test(e)?e:new URL(e).href,mD=new Set([301,302,303,307,308]);Object.defineProperty(Xn,"redirect",{value:function(t,n=302){if(!mD.has(n))throw new RangeError("Invalid status code");return new Xn(null,{status:n,headers:{location:pD(t)}})},writable:!0,configurable:!0});Object.defineProperty(Xn,"json",{value:function(t,n){let i=JSON.stringify(t);if(i===void 0)throw new TypeError("The data is not JSON serializable");let r=n?.headers,o;return r?(o=new Headers(r),o.has("content-type")||o.set("content-type","application/json")):o={"content-type":"application/json"},new Xn(i,{status:n?.status??200,statusText:n?.statusText,headers:o})},writable:!0,configurable:!0});async function fD(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function MS(e,t,n){let i=s=>{e.cancel(s).catch(()=>{})};return t.on("close",i),t.on("error",i),(n??e.read()).then(a,r),e.closed.finally(()=>{t.off("close",i),t.off("error",i)});function r(s){s&&t.destroy(s)}function o(){e.read().then(a,r)}function a({done:s,value:l}){try{if(s)t.end();else if(!t.write(l))t.once("drain",o);else return e.read().then(a,r)}catch(c){r(c)}}}function xS(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:MS(e.getReader(),t)}var $m=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has("set-cookie")){let i=[];for(let[r,o]of e)r==="set-cookie"?i.push(o):n[r]=o;i.length>0&&(n["set-cookie"]=i)}else for(let[i,r]of e)n[i]=r;return t&&(n["content-type"]??=t),n},kl=Symbol("outgoingEnded"),RS=Symbol("incomingDraining"),gD=500,hD=64*1024*1024,DS=e=>{let t=e;if(e.destroyed||t[RS])return;if(t[RS]=!0,e instanceof _i.Http2ServerRequest){try{e.stream?.close?.(_i.constants.NGHTTP2_NO_ERROR)}catch{}return}let n=0,i=()=>{clearTimeout(o),e.off("data",a),e.off("end",i),e.off("error",i)},r=()=>{i();let s=e.socket;s&&!s.destroyed&&s.destroySoon()},o=setTimeout(r,gD);o.unref?.();let a=s=>{n+=s.length,n>hD&&r()};e.on("data",a),e.on("end",i),e.on("error",i),e.resume()},yD=(e,t,n,i)=>()=>{t.errored?(wS(t),e[Nm](t.errored.toString())):n.writableFinished||(wS(t),e[Nm]("Client connection prematurely closed.")),i&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{DS(t)})})},vD=e=>{if(!(di in e))return!1;let t=e[di][1];return t===null||typeof t=="string"||t instanceof Uint8Array},bD=()=>new Response(null,{status:400}),jS=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),wl=(e,t)=>{let n=e instanceof Error?e:new Error("unknown error",{cause:e});n.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${n.message}`),t.destroy(n))},Lm=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},US=async(e,t)=>{let[n,i,r]=e[di];if(!r){i===null?(t.writeHead(n),t.end()):typeof i=="string"?(t.writeHead(n,{"Content-Type":Ni,"Content-Length":Buffer.byteLength(i)}),t.end(i)):i instanceof Uint8Array?(t.writeHead(n,{"Content-Type":Ni,"Content-Length":i.byteLength}),t.end(i)):i instanceof Blob?(t.writeHead(n,{"Content-Type":Ni,"Content-Length":i.size}),t.end(new Uint8Array(await i.arrayBuffer()))):(t.writeHead(n,{"Content-Type":Ni}),Lm(t),await xS(i,t)?.catch(a=>wl(a,t))),t[kl]?.();return}let o=!1;if(r instanceof Headers)o=r.has("content-length"),r=$m(r,i===null?void 0:Ni);else if(Array.isArray(r)){let a=new Headers(r);o=a.has("content-length"),r=$m(a,i===null?void 0:Ni)}else for(let a in r)if(a.length===14&&a.toLowerCase()==="content-length"){o=!0;break}o||(typeof i=="string"?r["Content-Length"]=Buffer.byteLength(i):i instanceof Uint8Array?r["Content-Length"]=i.byteLength:i instanceof Blob&&(r["Content-Length"]=i.size)),t.writeHead(n,r),i==null?t.end():typeof i=="string"||i instanceof Uint8Array?t.end(i):i instanceof Blob?t.end(new Uint8Array(await i.arrayBuffer())):(Lm(t),await xS(i,t)?.catch(a=>wl(a,t))),t[kl]?.()},FS=e=>typeof e.then=="function",SD=async(e,t,n={})=>{if(FS(e))if(n.errorHandler)try{e=await e}catch(r){let o=await n.errorHandler(r);if(!o)return;e=o}else e=await e.catch(jS);if(di in e)return US(e,t);let i=$m(e.headers,e.body===null?void 0:Ni);if(e.body){let r=e.body.getReader(),o=[],a=!1,s;if(i["transfer-encoding"]!=="chunked"){let l=2;for(let c=0;c<l;c++){s||=r.read();let u=await fD(s).catch(d=>{console.error(d),a=!0});if(!u){if(c===1){await new Promise(d=>setTimeout(d)),l=3;continue}break}if(s=void 0,u.value&&o.push(u.value),u.done){a=!0;break}}a&&!("content-length"in i)&&(i["content-length"]=o.reduce((c,u)=>c+u.length,0))}t.writeHead(e.status,i),o.forEach(l=>{t.write(l)}),a?t.end():(o.length===0&&Lm(t),await MS(r,t,s))}else i[SS]||(t.writeHead(e.status,i),t.end());t[kl]?.()},kD=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==oa&&(Object.defineProperty(global,"Request",{value:oa}),Object.defineProperty(global,"Response",{value:Xn})),async(i,r)=>{let o,a,s=!1,l=!1,c=()=>{!a||l||(l=!0,r.on("close",yD(a,i,r,s)))};try{if(a=dD(i,t.hostname),s=n&&!(i.method==="GET"||i.method==="HEAD"),s&&(i[IS]=!0,i instanceof _i.Http2ServerRequest&&(r[kl]=()=>{i.readableEnded||setTimeout(()=>{i.readableEnded||setTimeout(()=>{i.destroy(),r.destroy()})})})),o=e(a,{incoming:i,outgoing:r}),!FS(o)&&vD(o))return s&&!i.readableEnded&&r.once("finish",()=>{i.readableEnded||DS(i)}),US(o,r);c()}catch(u){if(o)return wl(u,r);if(t.errorHandler){if(c(),o=await t.errorHandler(a?u:XM(u)),!o)return}else a?o=jS(u):o=bD()}try{return await SD(o,r,t)}catch(u){return wl(u,r)}}},wD=globalThis.CloseEvent??class extends Event{#e;constructor(e,t={}){super(e,t),this.#e=t}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},ED=globalThis.ErrorEvent??class extends Event{#e;constructor(e,t={}){super(e,t),this.#e=t}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},AD=()=>Symbol("connection"),zS=Symbol("CONNECTION_SYMBOL_KEY"),qS=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),TD=new Set(["connection","content-length","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-accept","sec-websocket-extensions","sec-websocket-protocol"]),VS=(e,t)=>{t&&t.forEach((n,i)=>{TD.has(i.toLowerCase())||e.push(`${i}: ${n}`)})},OS=(e,t,n)=>{let i=["Connection: close","Content-Length: 0"];VS(i,n),e.end(`HTTP/1.1 ${t.toString()} ${El.STATUS_CODES[t]??""}\r
|
|
347
|
+
${n}`}function Gc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Kc(e,t,n){let i=new Set;for(let r of e)i.has(r)&&n.addIssue({code:"custom",path:[t],message:`Duplicate value: ${r}`}),i.add(r)}var lP=O(()=>{"use strict"});var uP=O(()=>{"use strict"});function Xv(e,t,n,i,r,o=!1){let a=["completed","failed","cancelled"].includes(t);return{...e,revision:e.revision+1,status:t,attempt_count:t==="executing"&&e.status!=="verifying"&&!o?(e.attempt_count??0)+1:e.attempt_count,status_reason:["blocked","failed","cancelled"].includes(t)?r??n?.summary??`Task moved to ${t}.`:null,updated_at:i,started_at:t==="executing"&&e.started_at===null?i:e.started_at,finished_at:a?i:null,result:a?n:null}}function dP(e,t){return e===`Orchestrator stopped without a persisted Gui finalization decision; lifecycle was fail-closed as blocked. (Run ${t}).`||e===`Finalization barrier missing; resume after a completed zaip-agent-finalizer Sub-Run with authoritative metadata (Run ${t}).`||e===`Finalization barrier evidence_missing; resume after passed typed Evidence linked to the same Task, Change, Execution, and Run (Run ${t}).`||e.startsWith(`Completion gates did not close Run ${t}:`)}function D5(e){return e.plan_ref?.execution_id??e.prepared_plan?.execution_id??null}function _P(e,t){if(e.status!=="blocked"||e.status_reason!==t.reason||D5(e)!==t.executionId||!dP(t.reason,t.runId))throw new Error(`Task ${e.id} is not recoverable from its own completion gate`)}var pP,Yv=O(()=>{"use strict";pP={draft:["planned","blocked","failed","cancelled"],planned:["executing","blocked","failed","cancelled"],executing:["verifying","failed","blocked","cancelled"],verifying:["executing","completed","failed","blocked","cancelled"],blocked:["executing","cancelled"],completed:[],failed:["executing"],cancelled:[]}});var at,Pp,j5,mP,U5,F5,z5,_o,ts,fP=O(()=>{"use strict";qe();Ko();at=Me(Ue(),1);Hv();Gv();Gv();lP();uP();Yv();Pp=at.z.string().datetime({offset:!0}),j5=at.z.string().regex(/^[a-f0-9]{64}$/),mP=at.z.string().startsWith("TASK-"),U5=at.z.string().startsWith("CHG-"),F5=at.z.string().startsWith("REQ-"),z5=at.z.string().startsWith("AC-"),_o=at.z.object({schema_version:at.z.literal(2),id:mP,revision:at.z.number().int().positive(),change_id:U5,title:at.z.string().min(1),short_name:at.z.string().min(1),objective:at.z.string().min(1),target_release:at.z.string().regex(/^[1-9]\d*\.(?:0|[1-9]\d*)$/).nullable().optional(),status:at.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),status_reason:at.z.string().min(1).nullable().optional(),attempt_count:at.z.number().int().nonnegative().optional(),risk:at.z.enum(["lite","standard","critical"]),priority:at.z.enum(["low","medium","high","urgent"]),owner:at.z.string().min(1).nullable(),requirement_ids:at.z.array(F5).min(1),acceptance_ids:at.z.array(z5).min(1),depends_on:at.z.array(mP),write_scopes:at.z.array(at.z.string().min(1)),runtime:rd.optional(),model_profile:yo.optional(),assurance_risk_signals:Np.optional(),assurance_risk_signals_source:at.z.enum(["explicit","risk_default"]).optional(),plan_revision:at.z.number().int().positive().nullable(),plan_hash:j5.nullable(),prepared_plan:Ri.optional(),plan_ref:Ka.optional(),created_at:Pp,updated_at:Pp,started_at:Pp.nullable(),finished_at:Pp.nullable(),result:Jv.nullable()}).strict().superRefine((e,t)=>{let n=e.plan_revision===null&&e.plan_hash===null;e.status==="draft"||n&&["blocked","failed","cancelled"].includes(e.status)?(!n||e.prepared_plan!==void 0||e.plan_ref!==void 0)&&t.addIssue({code:"custom",message:`${e.status} Task without materialization cannot contain a prepared plan`}):(e.plan_revision===null||e.plan_hash===null)&&t.addIssue({code:"custom",message:`${e.status} Task requires plan_revision and plan_hash`}),e.prepared_plan!==void 0&&e.plan_ref!==void 0&&t.addIssue({code:"custom",message:"Task cannot contain prepared_plan and plan_ref"}),e.plan_ref!==void 0&&e.plan_ref.hash!==e.plan_hash&&t.addIssue({code:"custom",path:["plan_ref"],message:"plan_ref must match plan_hash"}),e.prepared_plan!==void 0&&(e.prepared_plan.source.type!=="task"||e.prepared_plan.source.task_id!==e.id||e.prepared_plan.hash!==e.plan_hash)&&t.addIssue({code:"custom",path:["prepared_plan"],message:"prepared_plan must belong to the Task and match plan_hash"}),["completed","failed","cancelled"].includes(e.status)&&(e.finished_at===null||e.result===null)&&t.addIssue({code:"custom",message:"terminal Task requires finished_at and result"}),["executing","verifying","completed"].includes(e.status)&&e.started_at===null&&t.addIssue({code:"custom",message:`${e.status} Task requires started_at`}),e.status==="completed"&&(e.result?.completed_run_id===null||e.result?.evidence_ids.length===0)&&t.addIssue({code:"custom",path:["result"],message:"completed Task requires completed_run_id and at least one Evidence"}),Kc(e.requirement_ids,"requirement_ids",t),Kc(e.acceptance_ids,"acceptance_ids",t),Kc(e.depends_on,"depends_on",t),Kc(e.write_scopes,"write_scopes",t)}),ts=class{constructor(t,n){this.filesystem=t;this.layout=n;if(n.version===1)throw new TypeError("TaskV2Repository requires a modern WorkspaceLayout")}filesystem;layout;async read(t){let n=await Ro(this.filesystem,this.layout,"task",t);if(n===null)throw new Error(`task not found: ${t}`);let i=qt(await this.filesystem.readText(n),_o);return{task:i.metadata,body:i.body}}async list(){let t=await this.filesystem.listFiles(this.layout.entityRoot("task"),".md");return Promise.all(t.map(async n=>qt(await this.filesystem.readText(n),_o).metadata))}async createDraft(t){if(t.modelProfile&&t.modelProfile.risk!==t.risk)throw new Error("Task model profile risk differs from Task risk");let i=(t.clock??new rt).now().toISOString(),r=_o.parse({schema_version:2,id:t.id,revision:1,change_id:t.changeId,title:t.title,short_name:t.shortName,objective:t.objective,target_release:t.targetRelease??null,status:"draft",attempt_count:0,risk:t.risk,...t.modelProfile===void 0?{}:{model_profile:t.modelProfile},priority:t.priority,owner:t.owner??null,requirement_ids:[...t.requirementIds],acceptance_ids:[...t.acceptanceIds],depends_on:[...t.dependsOn??[]],write_scopes:[...t.writeScopes??[]],plan_revision:null,plan_hash:null,created_at:i,updated_at:i,started_at:null,finished_at:null,result:null,assurance_risk_signals:cP(t.risk,t.assuranceRiskSignals),assurance_risk_signals_source:t.assuranceRiskSignals===void 0?"risk_default":"explicit"});return await this.filesystem.writeTextExclusive(this.path(r.id),this.serialize(r)),r}async setPreparedPlan(t,n){let i=Ri.parse(n);if(i.source.type!=="task"||i.source.task_id!==t)throw new TypeError(`Prepared plan source must be task ${t}`);let r=await this.read(t);if(r.task.status==="planned"&&r.task.prepared_plan?.hash===i.hash)return r.task;if(r.task.status!=="draft")throw new Error(`Task ${t} must be draft before prepare`);let o=i.blueprints.tasks.find(c=>c.id===t);if(o===void 0)throw new Error(`Prepared plan does not contain Task ${t}`);let a=[o.change_id===r.task.change_id?null:"change_id",o.title===r.task.title?null:"title",o.short_name===r.task.short_name?null:"short_name",o.objective===r.task.objective?null:"objective",o.risk===r.task.risk?null:"risk",o.priority===r.task.priority?null:"priority",o.owner===r.task.owner?null:"owner",Gc(o.requirement_ids,r.task.requirement_ids)?null:"requirement_ids",Gc(o.acceptance_ids,r.task.acceptance_ids)?null:"acceptance_ids",Gc(o.write_scopes,r.task.write_scopes)?null:"write_scopes"].filter(c=>c!==null),s=i.dag.nodes.find(c=>c.task_id===t);if((s===void 0||!Gc(s.depends_on,r.task.depends_on))&&a.push("depends_on"),a.length>0)throw new Error(`Prepared plan diverges from Task draft: ${a.join(", ")}`);let l=_o.parse({...r.task,revision:r.task.revision+1,status:"planned",plan_revision:i.revision,plan_hash:i.hash,prepared_plan:i,...o.model_profile===void 0?{}:{model_profile:o.model_profile},updated_at:i.prepared_at});return await this.write(l),l}async write(t,n=Kv(t)){await this.filesystem.writeTextAtomic(this.path(t.id),this.serialize(t,n))}async normalizePreparedPlan(t,n){let i=await this.read(t);if(i.task.plan_ref?.hash===n.hash)return i.task;if(i.task.prepared_plan?.hash!==n.hash)throw new Error(`Task ${t} does not contain PreparedPlan ${n.hash}`);let{prepared_plan:r,...o}=i.task,a=_o.parse({...o,revision:i.task.revision+1,plan_ref:Lc(n),updated_at:new Date().toISOString()});return await this.write(a),a}async normalizeBody(t){let n=await this.read(t);return await this.write(n.task),n.task}serialize(t,n=Kv(t)){return fn({metadata:_o.parse(t),body:n})}async transition(t,n,i=null,r=new rt,o=null){let a=await this.read(t);if(!pP[a.task.status].includes(n))throw new Error(`Invalid Task transition: ${a.task.status} -> ${n}`);let s=_o.parse(Xv(a.task,n,i,r.now().toISOString(),o));return await this.write(s),s}async recoverOwnCompletionGateBlock(t,n,i=new rt){let r=await this.read(t);_P(r.task,n);let o=_o.parse(Xv(r.task,"executing",null,i.now().toISOString(),null,!0));return await this.write(o),o}path(t){return this.layout.activePath("task",t)}}});var wt,Qv,Rge,eb=O(()=>{"use strict";qe();wt=Me(Ue(),1);Iv();qc();Vc();I0();oP();sP();fP();Hv();Yv();Qv=wt.z.string().datetime({offset:!0}),Rge=wt.z.object({id:wt.z.string().startsWith("TASK-"),title:wt.z.string().min(1),short_name:wt.z.string().min(1),status:wt.z.enum(["draft","planned","executing","verifying","completed","failed","blocked","cancelled"]),risk:wt.z.enum(["lite","standard","critical"]),priority:wt.z.enum(["low","medium","high","urgent"]),owner:wt.z.string().min(1).nullable().default(null),progress:wt.z.number().int().min(0).max(100),spec:wt.z.string().startsWith("SPEC-"),change:wt.z.string().startsWith("CHG-"),requirements:wt.z.array(wt.z.string().startsWith("REQ-")),depends_on:wt.z.array(wt.z.string().startsWith("TASK-")),human_decisions:wt.z.array(wt.z.string().startsWith("DEC-HUMAN-")),agent_decisions:wt.z.array(wt.z.string().startsWith("DEC-AI-")),created_at:Qv,started_at:Qv.nullable(),finished_at:Qv.nullable()}).strict()});function $p(e){return new Set(e.filter(t=>t.status!=="planned").flatMap(t=>t.dag.nodes.map(n=>n.task_id)))}var tb=O(()=>{"use strict"});function gP(e){let t=new Map,n=(i,r)=>i===null&&r===null?null:(i??0)+(r??0);for(let i of e){if(i.task_id===null)continue;let r=t.get(i.task_id)??{duration_ms:null,tokens:null,cost_brl:null};t.set(i.task_id,{duration_ms:n(r.duration_ms,i.phase==="execution"&&i.parent_run_id==null?i.duration_ms:null),tokens:n(r.tokens,i.usage.total.tokens.total),cost_brl:n(r.cost_brl,i.usage.total.cost.brl)})}return t}function Xc(e,t){let n=e.filter(a=>a.status==="completed").length,i=t.filter(a=>a.status!=="running"),r=i.filter(a=>a.status==="completed").length,o=t.filter(a=>a.work_type==="rework").length;return{completed_tasks:n,task_completion_rate:e.length===0?0:n/e.length,terminal_runs:i.length,successful_runs:r,terminal_success_rate:i.length===0?0:r/i.length,rework_rate:t.length===0?0:o/t.length}}var nb=O(()=>{"use strict"});function Lp(e){let t=e?.source_started_at??null,n=e?.source_finished_at??e?.source_occurred_at??null;return{source_started_at:t,source_finished_at:n,source_duration_ms:t===null||n===null?null:Math.max(0,Date.parse(n)-Date.parse(t)),capture_lag_ms:n===null||e===void 0?null:Math.max(0,Date.parse(e.occurred_at)-Date.parse(n))}}function Mp(e,t,n,i){let r=Date.parse(e),o=c=>{let u=c==null?Number.NaN:Date.parse(c);return Number.isFinite(u)?u:null},a=(c,u)=>{let d=o(c),_=o(u);return d!==null&&_!==null&&_>=d&&_>=r},s=[];for(let c of[...n,...i]){let u=c.source_started_at,d=c.source_finished_at;if(u!==void 0&&d!==void 0&&a(u,d)){s.push({...c,source_finished_at:d});continue}c.activity_kind==="retrospective_local_reconciliation"&&typeof c.source_occurred_at=="string"&&(o(c.source_occurred_at)??Number.NEGATIVE_INFINITY)>=r&&s.push({...c,source_started_at:e,source_finished_at:c.source_occurred_at})}s.sort((c,u)=>Date.parse(c.occurred_at)-Date.parse(u.occurred_at));let l=s.at(-1);return Lp(l===void 0?void 0:{occurred_at:l.occurred_at,source_occurred_at:l.source_occurred_at??void 0,source_started_at:l.source_started_at,source_finished_at:l.source_finished_at})}function hP(e){function t(n,i){let r=new Set([...i===null?[]:e.prds.filter(c=>c.id===i).map(c=>c.creation_run_id),...e.specs.filter(c=>n.has(c.id)).map(c=>c.creation_run_id)].filter(c=>c!=null)),o=new Set(e.changes.filter(c=>i!==null&&c.source.type==="prd"&&c.source.prd_id===i||(c.source.type==="spec"||c.source.type==="prd")&&c.source.spec_id!==null&&c.source.spec_id!==void 0&&n.has(c.source.spec_id)).map(c=>c.id)),a=new Set(e.tasks.filter(c=>o.has(c.change_id)).map(c=>c.id)),s=new Set(e.executions.filter(c=>i!==null&&c.origin.type==="prd"&&c.origin.prd_id===i||c.origin.type==="spec"&&c.origin.spec_id!==void 0&&n.has(c.origin.spec_id)||c.dag.nodes.some(u=>a.has(u.task_id))).map(c=>c.id)),l=e.runs.filter(c=>{let u=c.fold.run.spec_id!==null&&n.has(c.fold.run.spec_id)||c.fold.run.task_id!==null&&a.has(c.fold.run.task_id)||r.has(c.fold.run.run_id);return i===null?u:u||c.fold.run.prd_id===i||c.fold.run.execution_id!==null&&s.has(c.fold.run.execution_id)});return{changeIds:o,taskIds:a,executionIds:s,runs:l}}return{forSpec:n=>t(new Set([n]),null),forPrd:n=>t(new Set(e.specs.filter(i=>i.prd_id===n).map(i=>i.id)),n)}}var rb=O(()=>{"use strict"});function yP(e){let t=OC(e.map(n=>n.cost));return{conversation:ns(t.conversation),planning:ns(t.planning),execution:ns(t.execution),total:ns(t.total),new_work:ns(t.work_types.new),rework:ns(t.work_types.rework)}}function ns(e){return{events:e.usage_event_count,tokens:e.tokens,cost:e.cost,coverage:e.coverage}}function jp(e){return{human:e.filter(t=>t.origin==="human").length,agent:e.filter(t=>t.origin==="agent").length}}function Up(e,t){let n=[e.conversation,e.planning,e.execution],i=Object.values(t).map(r=>r.total);return{phase_tokens_match_total:Dp(n.map(r=>r.tokens.total),e.total.tokens.total),phase_usd_match_total:Dp(n.map(r=>r.cost.usd),e.total.cost.usd),phase_brl_match_total:Dp(n.map(r=>r.cost.brl),e.total.cost.brl),origin_tokens_match_total:Dp(i.map(r=>r.tokens.total),e.total.tokens.total)}}function Dp(e,t){let n=e.filter(i=>i!==null);return t===null?n.length===0:Math.abs(n.reduce((i,r)=>i+r,0)-t)<1e-9}function Fp(e){return e==="completed"?100:e==="verifying"?80:e==="executing"?50:["blocked","failed","cancelled"].includes(e)?0:10}function vP(e){return e==="planned"?"planning":["running","paused","verifying"].includes(e)?"executing":e}function bP(e,t){if(e==="delivered")return"completed";if(e==="blocked")return"blocked";if(e==="failed")return"failed";if(e==="cancelled")return"cancelled";let n=t.flatMap(i=>i===void 0?[]:[i.status]);return n.some(i=>["running","paused"].includes(i))?"executing":n.includes("verifying")?"verifying":n.length>0&&n.every(i=>i==="completed")?e==="active"?"verifying":"completed":e==="active"?"executing":n.includes("blocked")?"blocked":n.includes("failed")?"failed":(n.includes("planned")||["draft","ready"].includes(e),"planning")}function Yc(e){return e.filter(t=>t!==null).map(t=>new Date(t).toISOString()).sort().at(-1)??null}var Qc=O(()=>{"use strict";zn()});function SP(e){let t=e.fold.finished?.occurred_at??null,n=e.fold.effective_usage_records.findLast(l=>l.runtime)?.runtime,i=e.fold.effective_usage_records.at(-1),r=Mp(e.fold.run.occurred_at,t,e.fold.effective_usage_records,e.fold.records),o=e.fold.finished,a=typeof r.source_duration_ms=="number"&&r.source_duration_ms>=0?r.source_duration_ms:typeof o?.duration_ms=="number"&&o.duration_ms>=0&&(o.duration_provenance==="observed"||o.duration_provenance==="reconciled"||o.duration_provenance==="legacy_inferred")?o.duration_ms:null,s=typeof r.source_duration_ms=="number"&&r.source_duration_ms>=0?"observed":a===null?"unavailable":o?.duration_provenance??"unavailable";return{id:e.fold.run.run_id,artifact_path:e.artifactPath,status:e.fold.status,phase:e.fold.records.findLast(l=>"phase"in l)?.phase??e.fold.run.phase,entrypoint:e.fold.run.entrypoint,work_type:e.fold.run.work_type,run_role:G_(e.fold.run),run_kind:Py(e.fold.run),run_purpose:$y(e.fold.run),requires_finalizer:Ly(e.fold.run),parent_run_id:e.fold.run.parent_run_id,client:e.fold.run.client,agent:e.fold.run.agent,agent_name:q5(e.fold.run.agent,e.fold.run.agent_name),provider:i?.provider??e.fold.run.provider,model:e.fold.run.model,reasoning_effort:e.fold.run.reasoning_effort??null,...V5(e.fold),...W5(e.fold),service_tier:n?.service_tier??null,conversation_id:e.fold.run.conversation_id,execution_id:e.fold.run.execution_id,task_id:e.fold.run.task_id,spec_id:e.fold.run.spec_id,prd_id:e.fold.run.prd_id,change_id:e.fold.run.change_id,started_at:e.fold.run.occurred_at,finished_at:t,duration_ms:a,duration_started_at:a===null?null:o?.started_at??e.fold.run.occurred_at,duration_provenance:s,...r,pricing_segments:e.fold.effective_usage_records.map(l=>({phase:l.phase,provider:l.provider,model:l.model,service_tier:l.runtime?.service_tier??n?.service_tier??null,input_tokens:l.tokens.input,cached_input_tokens:l.tokens.cached_input,output_tokens:l.tokens.output,reasoning_tokens:l.tokens.reasoning,total_tokens:l.tokens.total,recorded_usd:l.cost.usd,recorded_brl:l.cost.brl,recorded_fx_rate:l.cost.fx_rate??null})),usage:yP([e])}}function q5(e,t){if(e==="codex")return"codex";let n=t??e;return n.startsWith("agent-")?`zaip-agent-${n.slice(6)}`:n}function V5(e){let t=new Set([...e.provider_invocation_records.map(i=>i.effective.model),...e.effective_usage_records.map(i=>i.model)].filter(i=>i!==null)),n=new Set([...e.provider_invocation_records.map(i=>i.effective.reasoning_effort),...e.effective_usage_records.map(i=>i.runtime?.reasoning_effort??null)].filter(i=>i!==null));return{effective_model:t.size===1?[...t][0]??null:null,effective_reasoning_effort:n.size===1?[...n][0]??null:null,effective_config_mixed:t.size>1||n.size>1}}function W5(e){let t=new Set([...e.model_selection_records.map(n=>n.invocation_id),...e.provider_invocation_records.map(n=>n.invocation_id)]);return t.size===0?{call_count:null,terminal_call_count:null,failed_call_count:null,cancelled_call_count:null}:{call_count:t.size,terminal_call_count:e.provider_invocation_records.length,failed_call_count:e.provider_invocation_records.filter(n=>n.status==="failed").length,cancelled_call_count:e.provider_invocation_records.filter(n=>n.status==="cancelled").length}}function kP(e,t){return e!==null&&e>=0?e:null}var ib=O(()=>{"use strict";xc();rb();Qc()});function oi(e){return e.map(t=>typeof t.source_duration_ms=="number"&&t.source_duration_ms>=0?{...t,duration_ms:t.source_duration_ms,duration_provenance:"observed",estimation_basis:null}:typeof t.duration_ms=="number"&&t.duration_ms>=0&&(t.duration_provenance==="observed"||t.duration_provenance==="reconciled"||t.duration_provenance==="legacy_inferred")?{...t,estimation_basis:null}:{...t,duration_ms:null,duration_provenance:"unavailable",estimation_basis:null})}var zp=O(()=>{"use strict"});function EP(e,t){let n=new Set(e.dag.nodes.map(_=>_.task_id)),i=new Map(t.changes.map(_=>[_.id,_])),r=new Map(t.specs.map(_=>[_.id,_])),o=new Set,a=new Set,s=_=>{o.add(_);let p=r.get(_),g=p?.prd_id??p?.parent_id??null;g!==null&&a.add(g)};e.origin.type==="spec"&&s(e.origin.spec_id),e.origin.type==="prd"&&a.add(e.origin.prd_id);for(let _ of t.tasks){if(!n.has(_.id))continue;let p=i.get(_.change_id)?.source;p&&((p.type==="spec"||p.type==="prd")&&p.spec_id&&s(p.spec_id),p.type==="prd"&&p.prd_id&&a.add(p.prd_id))}let l=t.runs.filter(_=>_.execution_id===e.id||_.task_id!==null&&n.has(_.task_id)),c=l.flatMap(_=>_.call_count===null?[]:[_.call_count]),u=l.filter(_=>_.run_purpose==="finalization"||_.agent==="agent-finalizer"||_.agent==="agent-task-finalizer"),d=new Set(u.flatMap(_=>_.status==="completed"&&_.task_id!==null?[_.task_id]:[]));return{agent_call_count:l.length,orchestrator_run_count:l.filter(_=>_.parent_run_id===null).length,subagent_run_count:l.filter(_=>_.parent_run_id!==null).length,finalizer_run_count:u.length,finalized_task_count:d.size,llm_call_count:c.reduce((_,p)=>_+p,0),llm_call_count_complete:c.length===l.length,task_count:n.size,spec_count:o.size,prd_count:a.size,duration_ms:B5(l.filter(_=>_.parent_run_id===null)),total_tokens:wP(l.map(_=>_.usage?.tokens.total??null)),cost_brl:wP(l.map(_=>_.usage?.cost.brl??null))}}function wP(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function B5(e){let t=e.flatMap(n=>typeof n.source_duration_ms=="number"&&n.source_duration_ms>=0?[n.source_duration_ms]:typeof n.duration_ms=="number"&&n.duration_ms>=0&&(n.duration_provenance==="observed"||n.duration_provenance==="reconciled"||n.duration_provenance==="legacy_inferred")?[n.duration_ms]:[]);return t.length===0?null:t.reduce((n,i)=>n+i,0)}var AP=O(()=>{"use strict"});function qp(e){let t=TP(e.from??null,"from"),n=TP(e.to??null,"to");if(t!==null&&n!==null&&t>n)throw new Error("from must not be after to");return{from:t,to:n}}function TP(e,t){if(e===null||e.length===0)return null;let n=/^\d{4}-\d{2}-\d{2}$/.test(e)?t==="to"?`${e}T23:59:59.999-03:00`:`${e}T00:00:00.000-03:00`:e,i=Date.parse(n);if(Number.isNaN(i))throw new Error(`${t} must be an ISO timestamp`);return new Date(i).toISOString()}var ob=O(()=>{"use strict"});function Mn(e){let t=n=>{let i=e.map(n),r=o=>{let a=o.filter(s=>s!==null);return a.length===0?null:a.reduce((s,l)=>s+l,0)};return{events:i.reduce((o,a)=>o+a.events,0),tokens:{input:r(i.map(o=>o.tokens.input)),cached_input:r(i.map(o=>o.tokens.cached_input)),output:r(i.map(o=>o.tokens.output)),reasoning:r(i.map(o=>o.tokens.reasoning)),total:r(i.map(o=>o.tokens.total))},cost:{usd:r(i.map(o=>o.cost.usd)),brl:r(i.map(o=>o.cost.brl))},coverage:{events:i.reduce((o,a)=>o+a.coverage.events,0),tokens:i.reduce((o,a)=>o+a.coverage.tokens,0),usd:i.reduce((o,a)=>o+a.coverage.usd,0),brl:i.reduce((o,a)=>o+a.coverage.brl,0)}}};return{conversation:t(n=>n.usage.conversation),planning:t(n=>n.usage.planning),execution:t(n=>n.usage.execution),total:t(n=>n.usage.total),new_work:t(n=>n.usage.new_work),rework:t(n=>n.usage.rework)}}function Vp(e){let t=oi(e.runs),n=wc(t),i=Mn(t),r={conversation:Mn(t.filter(o=>o.entrypoint==="conversation")),task:Mn(t.filter(o=>o.entrypoint==="task")),spec:Mn(t.filter(o=>o.entrypoint==="spec")),prd:Mn(t.filter(o=>o.entrypoint==="prd"))};return{...e,runs:t,origins:r,summary:{...e.summary,run_count:t.length,execution_duration_ms:xi(n)??0,execution_day_count:new Set(n.map(o=>o.started_at.slice(0,10))).size,source_latest_at:Yc([e.summary.source_latest_at,...t.map(o=>o.finished_at??o.started_at)]),quality:Xc(e.tasks,t),reconciliation:Up(i,r),usage:i}}}function sb(e){let t=[...e.taskIds].flatMap(r=>{let o=e.tasks.get(r);return o===void 0?[]:[o]}),n=e.decisions.filter(r=>r.scope_type==="change"&&e.changeIds.has(r.scope_id)||r.scope_type==="execution"&&e.executionIds.has(r.scope_id)),i=cb(e.runs);return{id:e.id,title:e.title,created_at:e.createdAt,updated_at:e.updatedAt,kind:e.kind,parent_id:e.parentId,artifact_path:e.artifactPath,lifecycle_status:e.lifecycleStatus,work_status:bP(e.lifecycleStatus,[...e.executionIds].map(r=>e.executions.get(r))),execution_ids:[...e.executionIds].sort(),task_ids:[...e.taskIds].sort(),planned_tasks:[...e.plannedTasks],canonical_run_ids:i.canonicalRuns.map(r=>r.id).sort(),run_ids:i.canonicalRuns.map(r=>r.id).sort(),root_execution_run_ids:i.rootExecutionRuns.map(r=>r.id).sort(),execution_count:e.executionIds.size,task_count:Math.max(e.taskIds.size,e.plannedTasks.length),run_count:i.canonicalRuns.length,duration_ms:i.observedRootDuration,observed_root_duration_ms:i.observedRootDuration,observed_lifecycle_duration_ms:i.observedLifecycleDuration,duration_coverage:{eligible_runs:i.rootExecutionRuns.length,known_runs:i.knownRootRuns.length,unknown_runs:i.rootExecutionRuns.length-i.knownRootRuns.length,coverage_ratio:i.rootExecutionRuns.length===0?1:i.knownRootRuns.length/i.rootExecutionRuns.length},duration_provenance:i.observedRootDuration===null?"unavailable":"observed",lifecycle_duration_coverage:i.lifecycleCoverage,lifecycle_duration_provenance:i.observedLifecycleDuration===null?"unavailable":"observed",decisions:jp(n),rework_run_count:i.canonicalRuns.filter(r=>r.work_type==="rework").length,quality:Xc(t,i.canonicalRuns),usage:Mn(i.canonicalRuns)}}function cb(e){let t=[...new Map(e.map(a=>[a.id,a])).values()],n=t.filter(a=>a.phase==="execution"&&a.parent_run_id==null),i=n.filter(a=>ab(a)!==null),r=t.filter(a=>a.parent_run_id==null),o=r.filter(a=>ab(a)!==null);return{canonicalRuns:t,rootExecutionRuns:n,knownRootRuns:i,observedRootDuration:xi(n),observedLifecycleDuration:Z5(r),lifecycleCoverage:{eligible_runs:r.length,known_runs:o.length,unknown_runs:r.length-o.length,coverage_ratio:r.length===0?1:o.length/r.length}}}function Z5(e){let t=e.flatMap(a=>{let s=ab(a),l=Date.parse(a.source_started_at??a.duration_started_at??a.started_at);return s!==null&&Number.isFinite(l)?[{start:l,end:l+s}]:[]}).toSorted((a,s)=>a.start-s.start),n=t[0];if(n===void 0)return null;let i=0,r=n.start,o=n.end;for(let a of t.slice(1))a.start<=o?o=Math.max(o,a.end):(i+=o-r,r=a.start,o=a.end);return i+o-r}function ab(e){return typeof e.source_duration_ms=="number"&&e.source_duration_ms>=0?e.source_duration_ms:typeof e.duration_ms=="number"&&e.duration_ms>=0&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")?e.duration_ms:null}function xP(e){function t(n,i){let r=new Set([...i===null?[]:e.prds.filter(c=>c.id===i).map(c=>c.creation_run_id),...e.specs.filter(c=>n.has(c.id)).map(c=>c.creation_run_id)].filter(c=>c!=null)),o=new Set(e.changes.filter(c=>i!==null&&c.source.type==="prd"&&c.source.prd_id===i||(c.source.type==="spec"||c.source.type==="prd")&&c.source.spec_id!==null&&c.source.spec_id!==void 0&&n.has(c.source.spec_id)).map(c=>c.id)),a=new Set(e.tasks.filter(c=>o.has(c.change_id)).map(c=>c.id)),s=new Set(e.executions.filter(c=>i!==null&&c.origin.type==="prd"&&c.origin.prd_id===i||c.origin.type==="spec"&&n.has(c.origin.spec_id)||c.dag.nodes.some(u=>a.has(u.task_id))).map(c=>c.id)),l=e.runs.filter(c=>c.spec_id!==null&&n.has(c.spec_id)||c.task_id!==null&&a.has(c.task_id)||r.has(c.id)||i!==null&&(c.prd_id===i||c.execution_id!==null&&s.has(c.execution_id)));return{changeIds:o,taskIds:a,executionIds:s,runs:l}}return{forSpec:n=>t(new Set([n]),null),forPrd:n=>t(new Set(e.specs.filter(i=>i.prd_id===n).map(i=>i.id)),n)}}var lb=O(()=>{"use strict";Ec();nb();zp();Qc()});function RP(e,t){let n=new Map(e.map(r=>[r.id,ub(r.prepared_plan)])),i=new Map(t.map(r=>{let o=ub(r.prepared_plan);if(o.length>0||r.prd_id===null)return[r.id,o];let a=e.find(s=>s.id===r.prd_id);return[r.id,a===void 0?[]:ub(a.prepared_plan,r.id)]}));return{byPrd:n,bySpec:i}}function OP(e){let t=new Map;for(let n of e){if(n.kind==="interaction")continue;let i=new Set(n.dag.nodes.map(r=>r.task_id));n.origin.type==="task"&&i.add(n.origin.task_id);for(let r of i)t.set(r,new Set([...t.get(r)??[],n.id]))}return new Map([...t].map(([n,i])=>[n,[...i].sort()]))}function ub(e,t){if(e==null||e.blueprints===void 0)return[];let n=new Map(e.blueprints.changes.map(r=>[r.id,r.source.type==="spec"||r.source.type==="prd"?r.source.spec_id??null:null])),i=new Map(e.dag.nodes.map(r=>[r.task_id,r.depends_on]));return e.blueprints.tasks.filter(r=>t===void 0||n.get(r.change_id)===t).map(r=>({id:r.id,title:r.title,objective:r.objective,depends_on:i.get(r.id)??[]}))}var CP=O(()=>{"use strict"});function NP(e){return typeof e=="number"&&e>0?Math.round(e*36e5/4e6):null}function PP(e,t){let n=e.filter(o=>(o.total_tokens??0)>0);if(n.length<7||t<n.length)return e.map(o=>IP(o));let i=n.reduce((o,a)=>o+(a.total_tokens??0),0),r=0;return e.map(o=>{if(!n.includes(o))return IP(o);let a=n.at(-1)===o?t-r:1+Math.floor((t-n.length)*(o.total_tokens??0)/i);return r+=a,{...o,duration:{known_sum:a,unknown:0,complete:!0,coverage_ratio:1}}})}function db(e,t){let n=PP(e.map(([r,o])=>({key:r,total_tokens:o.usage.total_tokens.known_sum,estimated_brl:o.usage.cost.known_sum,duration:Yo(r,o).value})),t),i=new Map(n.map(r=>[r.key,r.duration]));return Object.fromEntries(e.map(([r,o])=>[r,{...o,duration:i.get(r)??Yo(r,o).value}]))}function IP(e){if((e.total_tokens??0)<=0||e.duration.known_sum>0)return e;let t=NP(e.total_tokens);return t===null?e:{...e,duration:{known_sum:t,unknown:0,complete:!0,coverage_ratio:1}}}function el(e){let t=e.filter(i=>(i.phase===void 0||i.phase==="execution")&&i.parent_run_id==null),n=new Map;for(let i of t){let r=i.duration_started_at??i.started_at;if(!z_(r)||r===null)continue;let o=Date.parse(r),a=Wt(r,"day");if(!Number.isFinite(o)||a===null)continue;if(i.duration_ms===null||i.duration_ms<0){let l=n.get(a)??{intervals:[],known:0,unknown:0};l.unknown+=1,n.set(a,l);continue}let s=o+i.duration_ms;for(let l=o;l<=s;){let c=Wt(new Date(l).toISOString(),"day");if(c===null)break;let u=Math.min(s,J5(c)),d=n.get(c)??{intervals:[],known:0,unknown:0};if(d.intervals.push({start:l,end:u}),d.known+=1,n.set(c,d),u>=s)break;l=u}}return new Map([...n].map(([i,r])=>{let o=r.known+r.unknown;return[i,{value:{known_sum:G5(r.intervals),unknown:r.unknown,complete:r.unknown===0,coverage_ratio:o===0?1:r.known/o},population:{eligible_runs:o,known_runs:r.known,unknown_runs:r.unknown}}]}))}function Yo(e,t,n,i=!1){let r=ti[e]??0,o=e>=gn.cutoffDay?n:void 0;if(i&&r===0&&o===void 0)return H5();let a=i?o?.value:e<gn.cutoffDay?void 0:t.duration,s=a?.unknown??0,l=i?o?.population.eligible_runs??0:t.runs,c=i?o?.population.known_runs??0:t.runs-s;return{value:{known_sum:r+(a?.known_sum??0),unknown:s,complete:s===0,coverage_ratio:l===0?1:c/l},population:{eligible_runs:l,known_runs:c,unknown_runs:s}}}function H5(){return{value:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},population:{eligible_runs:0,known_runs:0,unknown_runs:0}}}function J5(e){let[t,n,i]=e.split("-").map(Number),r=new Date(Date.UTC(t,n-1,i+1)),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/Sao_Paulo",timeZoneName:"longOffset"}).formatToParts(r).find(s=>s.type==="timeZoneName")?.value??"GMT",a=/^GMT([+-])(\d{2}):(\d{2})$/.exec(o);return a===null?r.getTime():r.getTime()-(Number(a[2])*60+Number(a[3]))*6e4*(a[1]==="+"?1:-1)}function G5(e){let t=0,n=Number.NaN,i=Number.NaN;for(let r of e.toSorted((o,a)=>o.start-a.start))!Number.isFinite(n)||r.start>i?(Number.isFinite(n)&&(t+=i-n),n=r.start,i=r.end):i=Math.max(i,r.end);return Number.isFinite(n)?t+i-n:t}var _b=O(()=>{"use strict";Ma()});function K5(e,t){return(t.from===null||e>=t.from.slice(0,10))&&(t.to===null||e<=t.to.slice(0,10))}function $P(e,t){let n=d=>{let _=e.reduce((m,[,f])=>m+d(f).known_sum,0),p=e.reduce((m,[,f])=>m+d(f).unknown,0),g=e.reduce((m,[,f])=>m+f.runs,0);return{value:g===p?null:_,coverage:g===0?1:(g-p)/g}},i=e.map(([d,_])=>{let p=d<=gn.cutoffDay?ti[d]??0:0,g=d<gn.cutoffDay?void 0:_.duration;return{known_sum:p+(g?.known_sum??0),unknown:g?.unknown??0,runs:_.runs}}),r=i.reduce((d,_)=>d+_.known_sum,0),o=i.reduce((d,_)=>d+_.unknown,0),a=i.reduce((d,_)=>d+_.runs,0),s=a===o&&r===0?null:r,l={value:t.from===null&&t.to===null&&s!==null?JC(s):s,coverage:a===0?1:(a-o)/a},c=n(d=>d.usage.total_tokens),u=n(d=>d.usage.cost);return{duration_ms:l.value,tokens:c.value,cost_brl:u.value,coverage:{duration:l.coverage,tokens:c.coverage,cost:u.coverage},execution_day_count:i.filter(d=>d.known_sum>0).length}}function Wp(e,t){if(e===null)return[];let n=new Map;for(let[i,r]of Object.entries(e.days)){if(!K5(i,t))continue;let o=r.tasks.length>0?r.tasks:r.specs.length>0?r.specs:r.prds;for(let a of o){let s=n.get(a.id);if(s===void 0){n.set(a.id,structuredClone(a));continue}s.run_count+=a.run_count;for(let l of["duration","total_tokens","cost"])s.metrics[l].known_sum+=a.metrics[l].known_sum,s.metrics[l].unknown+=a.metrics[l].unknown,s.metrics[l].complete=s.metrics[l].unknown===0,s.metrics[l].coverage_ratio=s.run_count===0?1:(s.run_count-s.metrics[l].unknown)/s.run_count;(a.window_at??a.occurred_at)>(s.window_at??s.occurred_at)&&(s.status=a.status,s.risk=a.risk,a.window_at!==void 0&&(s.window_at=a.window_at))}}return[...n.values()]}function LP(e){let t={},n={};for(let i of e){let r=i.status??"unclassified",o=i.risk??"unclassified";t[r]=(t[r]??0)+1,n[o]=(n[o]??0)+1}return{total:e.length,statuses:t,risks:n}}function pb(e,t,n){let i=e8(),r={...i,tokens:{...i.tokens,total:Qo(e.metrics.total_tokens)},cost:{...i.cost,brl:Qo(e.metrics.cost)}};return{id:e.id,title:e.title??e.id,created_at:e.occurred_at,updated_at:e.window_at??null,kind:t,parent_id:e.parent_id,artifact_path:"",lifecycle_status:e.status??"unavailable",work_status:X5(e.status),execution_ids:[],task_ids:[],planned_tasks:[],canonical_run_ids:[],run_ids:[],root_execution_run_ids:[],execution_count:0,task_count:n,run_count:e.run_count,duration_ms:Qo(e.metrics.duration),observed_root_duration_ms:Qo(e.metrics.duration),observed_lifecycle_duration_ms:null,duration_coverage:Y5(e),duration_provenance:e.metrics.duration.complete?"observed":"unavailable",lifecycle_duration_coverage:Q5(),lifecycle_duration_provenance:"unavailable",decisions:{human:0,agent:0},rework_run_count:0,quality:{completed_tasks:0,task_completion_rate:0,terminal_runs:0,successful_runs:0,terminal_success_rate:0,rework_rate:0},usage:t8(i,r)}}function MP(e){let t=e.status,n=["completed","blocked","failed","cancelled"].includes(t??"");return{schema_version:2,id:e.id,revision:0,change_id:"",title:e.title??e.id,short_name:e.id,objective:"",status:t==="draft"||t==="planned"||t==="executing"||t==="verifying"||t==="completed"||t==="failed"||t==="blocked"||t==="cancelled"?t:"draft",attempt_count:t==="planned"||t==="draft"?0:null,risk:e.risk==="lite"||e.risk==="standard"||e.risk==="critical"?e.risk:"standard",priority:"medium",owner:null,requirement_ids:[],acceptance_ids:[],depends_on:[],write_scopes:[],created_at:e.occurred_at,updated_at:e.window_at??e.occurred_at,started_at:t==="executing"||t==="verifying"||n?e.occurred_at:null,finished_at:n?e.window_at??e.occurred_at:null,result:null,artifact_path:"",progress:n?1:0,spec_id:e.parent_id,execution_started:t==="executing"||t==="verifying"||n,execution_ids:[],execution_count:0,telemetry:{duration_ms:Qo(e.metrics.duration),tokens:Qo(e.metrics.total_tokens),cost_brl:Qo(e.metrics.cost)},test_count:0}}function DP(e){return e.map(t=>({task_id:t.id,duration_ms:t.metrics.duration.known_sum,total_tokens:t.metrics.total_tokens.known_sum,cost_brl:t.metrics.cost.known_sum,run_count:t.run_count})).sort((t,n)=>n.duration_ms-t.duration_ms||t.task_id.localeCompare(n.task_id)).slice(0,5)}function Qo(e){return e.known_sum===0&&e.unknown>0?null:e.known_sum}function X5(e){return e==="delivered"?"completed":["planning","executing","verifying","completed","blocked","failed","cancelled"].includes(e??"")?e:"planning"}function Y5(e){return{eligible_runs:e.run_count,known_runs:e.run_count-e.metrics.duration.unknown,unknown_runs:e.metrics.duration.unknown,coverage_ratio:e.metrics.duration.coverage_ratio}}function Q5(){return{eligible_runs:0,known_runs:0,unknown_runs:0,coverage_ratio:1}}function e8(){return{events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}}}function t8(e,t){return{conversation:e,planning:e,execution:e,total:t,new_work:e,rework:e}}var jP=O(()=>{"use strict";Ma()});function mb(e,t,n=!0){let i=[...new Map(e.map(c=>[c.id,c])).values()],r=n?i.filter(c=>Hp(c.finished_at??c.started_at,t)):i,o=r.filter(c=>c.phase==="execution"&&c.parent_run_id==null),a=fb(o,t),s=c=>{let u=c.filter(d=>d!==null);return u.length===0?null:Math.round(u.reduce((d,_)=>d+_,0)*1e9)/1e9},l=c=>c.length===0?1:c.filter(u=>u!==null).length/c.length;return{duration_ms:a===void 0||a.coverage_ratio===0?null:a.known_sum,tokens:s(r.map(c=>c.total_tokens)),cost_brl:s(r.map(c=>c.cost)),coverage:{duration:a?.coverage_ratio??1,tokens:l(r.map(c=>c.total_tokens)),cost:l(r.map(c=>c.cost))},execution_day_count:new Set(o.map(c=>Wt(c.duration_started_at??c.started_at,"day")).filter(c=>c!==null)).size}}function fb(e,t){let n=el(e),r=[...new Set([...Object.keys(ti),...n.keys()])].filter(c=>Bp(c,t)).map(c=>Yo(c,{runs:0},n.get(c),!0).value);if(r.length===0)return;let o=r.reduce((c,u)=>c+u.unknown,0),a=r.reduce((c,u)=>c+u.known_sum,0),s=[...n].filter(([c])=>Bp(c,t)).reduce((c,[,u])=>c+u.population.eligible_runs,0),l=[...n].filter(([c])=>Bp(c,t)).reduce((c,[,u])=>c+u.population.known_runs,0);return{known_sum:a,unknown:o,complete:o===0,coverage_ratio:s===0?1:l/s}}function Bp(e,t){return(t.from===null||e>=t.from.slice(0,10))&&(t.to===null||e<=t.to.slice(0,10))}async function nl(e,t,n={},i={}){if(t.version===1)throw new Error("Operations projection requires a modern WorkspaceLayout");let r=new Bt(e),o=qp(n),[a,s,l,c]=await Promise.all([r.readDailyReadModels("overview"),r.readDailyReadModels("tasks"),r.readDailyReadModels("specs"),r.readDailyReadModels("prds")]);if(a===null)throw new Error("Lifecycle daily overview is not initialized");let u=Object.entries(a.days).filter(([L])=>Bp(L,o)).map(([L,J])=>[L,J.overview]),d=$P(u,o),_={runs:u.reduce((L,[,J])=>L+J.runs,0)},p=u8(),g={...p,tokens:{...p.tokens,total:d.tokens},cost:{...p.cost,brl:d.cost_brl}},m=d.coverage,f=db(u,d.duration_ms??0),v=Wp(s,o),S=Wp(c,o),b=Wp(l,o),h=LP(v),k=h.statuses,P=h.risks,U=new Map;for(let L of v)L.parent_id!==null&&U.set(L.parent_id,(U.get(L.parent_id)??0)+1);let $=new Map(b.map(L=>[L.id,L.parent_id])),B=S.map(L=>pb(L,"prd",v.filter(J=>J.parent_id===L.id).length+[...U].filter(([J])=>$.get(J)===L.id).reduce((J,[,le])=>J+le,0))),z=b.map(L=>pb(L,"spec",U.get(L.id)??0)),R=DP(v);return{schema_version:2,layout_version:t.version,readonly:!0,source:".agents/records",filters:o,summary:{prd_count:B.length,spec_count:z.length,execution_count:0,task_count:h.total,run_count:_.runs,overview_metrics:{duration_ms:d.duration_ms,execution_day_count:d.execution_day_count,tokens:d.tokens,cost_brl:d.cost_brl,prd_count:B.length,spec_count:z.length,selected_counts:{prds:B.length,specs:z.length},task_count:h.total,completed_prd_count:B.filter(L=>L.work_status==="completed").length,completed_spec_count:z.filter(L=>L.work_status==="completed").length,completed_task_count:k.completed??0,task_status_counts:k,task_risk_counts:P,top_tasks:R,latest_task_created_at:v.map(L=>L.occurred_at).sort().at(-1)??null,coverage:{duration:m.duration,tokens:m.tokens,cost:m.cost},data_source:"lifecycle_manifest_summary",partial:!0},decisions:{human:0,agent:0},source_latest_at:a.source_latest_at,quality:{completed_tasks:0,task_completion_rate:0,terminal_runs:0,successful_runs:0,terminal_success_rate:0,rework_rate:0},reconciliation:{phase_tokens_match_total:!1,phase_usd_match_total:!1,phase_brl_match_total:!1,origin_tokens_match_total:!1},usage:tl(p,g),periods:{daily:f}},origins:{conversation:tl(p,p),task:tl(p,p),spec:tl(p,p),prd:tl(p,p)},prds:B,specs:z,tasks:i.includeBoardTasks?v.map(MP):[],changes:[],executions:[],runs:[],decisions:[],evidences:[],validations:[]}}function n8(e,t){return Object.fromEntries(e.map(([n,i])=>{let r=fb(t.filter(i8),{from:n,to:n});return[n,{...i,...r===void 0?{}:{duration:r}}]}))}function r8(e,t){let n={},i={},r=0;for(let o of e){let s=o.finished_at??(typeof o.data?.finished_at=="string"?o.data.finished_at:null)??o.updated_at;if(!Hp(s,t))continue;r+=1;let l=o.status??"unclassified",c=o.risk??"unclassified";n[l]=(n[l]??0)+1,i[c]=(i[c]??0)+1}return{total:r,statuses:n,risks:i}}function Hp(e,t){let n=new Date(e).toISOString();return(t.from===null||n>=t.from)&&(t.to===null||n<=t.to)}function UP(e,t){let n=new Map;for(let i of e){if(i.task_id===null||!t.has(i.task_id))continue;let r=n.get(i.task_id)??{task_id:i.task_id,duration_ms:0,total_tokens:0,cost_brl:0,run_count:0,runs:[]};r.runs.push(i),r.total_tokens+=i.total_tokens??0,r.cost_brl+=i.cost??0,r.run_count+=1,n.set(i.task_id,r)}return[...n.values()].map(({runs:i,...r})=>({...r,duration_ms:xi(i)??0})).sort((i,r)=>r.duration_ms-i.duration_ms||i.task_id.localeCompare(r.task_id)).slice(0,5)}function i8(e){return e.phase==="execution"&&e.parent_run_id==null}function o8(e,t,n){let i=t===null?null:Wt(t,"day"),r=n===null?null:Wt(n,"day");return Object.entries(a8(e)).filter(([o])=>(i===null||o>=i)&&(r===null||o<=r))}function a8(e){let t=[...new Map((e.run_metrics??[]).map(o=>[o.id,o])).values()],n=Object.values(e.periods.daily).reduce((o,a)=>o+a.runs,0);if(t.length===0||t.length!==n)return e.periods.daily;let i=new Map;for(let o of t){let a=Wt(o.finished_at??o.started_at,"day");a!==null&&i.set(a,[...i.get(a)??[],o])}let r=new Set([...Object.keys(e.periods.daily),...i.keys()]);return Object.fromEntries([...r].map(o=>{let a=e.periods.daily[o]??s8(e.usage.cost.currency),s=i.get(o)??[];return[o,{...a,runs:s.length,usage:{...a.usage,total_tokens:Zp(s.map(l=>l.total_tokens)),cost:{...Zp(s.map(l=>l.cost)),currency:a.usage.cost.currency??e.usage.cost.currency}},events:Zp(s.map(l=>l.events))}]}))}function Zp(e){let t=e.filter(i=>i!==null),n=e.length-t.length;return{known_sum:t.reduce((i,r)=>i+r,0),unknown:n,complete:n===0,coverage_ratio:e.length===0?1:t.length/e.length}}function s8(e){let t=Zp([]);return{prds:0,specs:0,tasks:0,validations:0,evidences:0,runs:0,usage:{input_tokens:t,output_tokens:t,total_tokens:t,cost:{...t,currency:e}},events:t}}function c8(e,t,n){return UP((e.run_metrics??[]).filter(i=>Hp(i.finished_at??i.started_at,t)),n)}function l8(e,t){return Hp(e.updated_at,t)}function u8(){return{events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}}}function tl(e,t){return{conversation:e,planning:e,execution:e,total:t,new_work:e,rework:e}}function d8(e){let t=n=>e.length===0?1:n/e.length;return{duration:t(e.filter(n=>n.duration_ms!==null).length),tokens:t(e.filter(n=>n.total_tokens!==null).length),cost:t(e.filter(n=>n.cost!==null).length)}}var gb=O(()=>{"use strict";ri();Ma();Ec();_b();ob();jP()});function FP(e){return[...e].sort((t,n)=>n.started_at.localeCompare(t.started_at)||n.id.localeCompare(t.id))}var zP=O(()=>{"use strict"});async function qP(e,t,n){if(t.version===1)throw new TypeError("Operations projection requires a modern layout");let i=(await Promise.all(p8(t.entityRoot("run"),n).map(o=>e.listFiles(o,".jsonl")))).flat();return(await _8(i,32,async o=>{let a=qa(za(await e.readText(o))),s=a.finished?.occurred_at??a.run.occurred_at;return(n.from!==null||n.to!==null)&&!m8(s,n)?null:{fold:a,artifactPath:o,cost:{run:a.run,records:a.records,effective_usage_records:a.effective_usage_records}}})).filter(o=>o!==null).sort((o,a)=>o.fold.run.run_id.localeCompare(a.fold.run.run_id))}async function _8(e,t,n){let i=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);i.push(...await Promise.all(o.map(n)))}return i}function p8(e,t){return[e]}function m8(e,t){let n=new Date(e).toISOString();return(t.from===null||n>=t.from)&&(t.to===null||n<=t.to)}var VP=O(()=>{"use strict";xc()});async function Jp(e,t,n){let i=new Map(t.map(o=>[o.id,0])),r=new Map;for(let o of t)r.set(o.change_id,[...r.get(o.change_id)??[],o]);for(let[o,a]of r){let s=n(o).replace(/\\/g,"/"),l=s.slice(0,s.lastIndexOf("/")),c;try{c=await e.listFiles(l)}catch{continue}let u=c.filter(d=>d.replace(/\\/g,"/").includes("/artifacts/tests/")&&/\.(?:md|json|jsonl|txt|log)$/i.test(d));for(let d of u){let _;try{_=await e.readText(d)}catch{continue}for(let p of a)_.includes(p.id)&&i.set(p.id,(i.get(p.id)??0)+1)}}return i}var hb=O(()=>{"use strict"});function ZP(e,t){let n=mb(e.map(i=>({id:i.id,started_at:i.started_at,finished_at:i.finished_at??null,phase:i.phase??null,parent_run_id:i.parent_run_id??null,duration_started_at:i.source_started_at??i.duration_started_at??null,duration_ms:i.source_duration_ms!==null&&i.source_duration_ms!==void 0?i.source_duration_ms:i.duration_ms,total_tokens:i.usage.total.tokens.total,cost:i.usage.total.cost.brl})),t,!1);return{duration_ms:n.duration_ms,execution_day_count:n.execution_day_count,tokens:n.tokens,cost_brl:n.cost_brl}}async function il(e,t,n={},i={}){if(t.version===1)throw new Error("Operations projection requires a modern WorkspaceLayout");let r=qp(n),o=new Bt(e),a=new Ho(e,t),s=new Jo(e,t),l=new Go(e,t),c=new lo(e,t),u=new ts(e,t),d=new J_(e,t),[_,p]=await Promise.all([o.readEntities(),i.overviewOnly?Promise.resolve([]):qP(e,t,r)]);if(_.length===0&&await o.readSummary()===null&&!await e.exists(".agents/records/lifecycle/.gitkeep"))throw new Error("Lifecycle manifest is not initialized; run `zaip manifest rebuild --confirm-full-scan`");let g=rl(_,"prd"),m=rl(_,"spec"),f=rl(_,"change"),v=rl(_,"execution"),S=rl(_,"task"),b=h8(_),h=g8(_),k=f8(_),P=p.map(SP),U=g.filter(D=>BP(D.status,D.updated_at,r)),$=m.filter(D=>BP(D.status,D.updated_at,r)),B=f.filter(D=>yb(D,r)),z=v.filter(D=>yb(D,r)),R=S.filter(D=>yb(D,r)),L=b.filter(D=>rs(D.created_at,r)),J=h.filter(D=>rs(D.observed_at,r)),le=k.filter(D=>rs(D.executed_at,r)),j=P.filter(D=>rs(D.finished_at??D.started_at,r)),Q=oi(j),C=new Map(f.map(D=>[D.id,D])),F=new Map(S.map(D=>[D.id,D])),X=new Map(v.map(D=>[D.id,D])),ne=xP({changes:f,tasks:S,executions:v,prds:g,specs:m,runs:Q}),ve=i.overviewOnly||i.skipTestArtifacts?new Map:await Jp(e,R,D=>l.path(D)),ge=$p(v),q=OP(v),A=gP(Q),I=RP(g,m),he=U.map(D=>{let Ne=ne.forPrd(D.id);return sb({id:D.id,title:D.title,createdAt:D.created_at,updatedAt:D.updated_at,kind:"prd",parentId:null,artifactPath:a.path(D.id),lifecycleStatus:D.status,...Ne,decisions:b,executions:X,tasks:F,plannedTasks:I.byPrd.get(D.id)??[]})}),me=$.map(D=>{let Ne=ne.forSpec(D.id);return sb({id:D.id,title:D.title,createdAt:D.created_at,updatedAt:D.updated_at,kind:"spec",parentId:D.prd_id,artifactPath:s.path(D.id),lifecycleStatus:D.status,...Ne,decisions:b,executions:X,tasks:F,plannedTasks:I.bySpec.get(D.id)??[]})}),Le=R.map(D=>{let Ne=C.get(D.change_id);return{...D,attempt_count:D.attempt_count??null,artifact_path:u.path(D.id),progress:Fp(D.status),test_count:ve.get(D.id)??0,spec_id:Ne?.source.type==="spec"||Ne?.source.type==="prd"?Ne.source.spec_id:null,execution_started:ge.has(D.id),execution_ids:q.get(D.id)??[],execution_count:q.get(D.id)?.length??0,telemetry:A.get(D.id)??null}}),Ce=Mn(Q),Pe=wc(Q),rn=ZP(Q,r),Y=i.overviewOnly?await nl(e,t,r):null,ce=WP(R,D=>D.status),$e=WP(R,D=>D.risk),Xe=HP(U,$),x={prd_count:he.length,spec_count:me.length,selected_counts:{prds:he.length,specs:me.length},task_count:R.length,completed_prd_count:Xe.prds,completed_spec_count:Xe.specs,completed_task_count:ce.completed??0,task_status_counts:ce,task_risk_counts:$e,latest_task_created_at:Yc(R.map(D=>D.created_at))},se={conversation:Mn(Q.filter(D=>D.entrypoint==="conversation")),task:Mn(Q.filter(D=>D.entrypoint==="task")),spec:Mn(Q.filter(D=>D.entrypoint==="spec")),prd:Mn(Q.filter(D=>D.entrypoint==="prd"))};return{schema_version:2,layout_version:t.version,readonly:!0,source:".agents/records",filters:r,summary:{prd_count:he.length,spec_count:me.length,execution_count:z.length,task_count:R.length,run_count:Q.length,execution_duration_ms:xi(Pe)??0,execution_day_count:new Set(Pe.map(D=>D.started_at.slice(0,10))).size,overview_metrics:Y?.summary.overview_metrics===void 0?{...rn,...x,data_source:"run_records",partial:!1}:{...Y.summary.overview_metrics,...x,partial:!1},decisions:jp(L),source_latest_at:Y?.summary.source_latest_at??Yc([...U.map(D=>D.updated_at),...$.map(D=>D.updated_at),...B.map(D=>D.updated_at),...z.map(D=>D.updated_at),...R.map(D=>D.updated_at),...L.map(D=>D.created_at),...Q.map(D=>D.finished_at??D.started_at)]),quality:Xc(R,Q),reconciliation:Up(Ce,se),usage:Y?.summary.usage??Ce},origins:se,prds:he,specs:me,tasks:Le,changes:i.overviewOnly&&!i.includeOverviewChanges?[]:B.map(D=>({...D,artifact_path:l.path(D.id)})),executions:i.overviewOnly?[]:z.map(D=>({...D,kind:D.kind??"delivery",client_turn_id:D.client_turn_id??null,...EP(D,{runs:Q.map(Ne=>({agent:Ne.agent,call_count:Ne.call_count,duration_ms:Ne.duration_ms,...Ne.duration_provenance===void 0?{}:{duration_provenance:Ne.duration_provenance},execution_id:Ne.execution_id,finished_at:Ne.finished_at,parent_run_id:Ne.parent_run_id,run_purpose:Ne.run_purpose,source_duration_ms:Ne.source_duration_ms??null,started_at:Ne.started_at,status:Ne.status,task_id:Ne.task_id,usage:Ne.usage.total})),tasks:R,changes:B,specs:$}),artifact_path:c.path(D.id),work_status:vP(D.status)})),runs:i.overviewOnly?[]:FP(Q),evidences:J,validations:le,decisions:i.overviewOnly?[]:L.map(D=>({id:D.id,title:D.title,origin:D.origin,scope_type:D.scope_type,scope_id:D.scope_id,artifact_path:d.path(D.scope_type,D.scope_id,D.id),created_at:D.created_at}))}}function HP(e,t){return{prds:e.filter(n=>n.status==="delivered").length,specs:t.filter(n=>n.status==="delivered").length}}function WP(e,t){return e.reduce((n,i)=>{let r=t(i);return n[r]=(n[r]??0)+1,n},{})}function f8(e){return e.flatMap(t=>{let n=t.data;return t.kind!=="validation"||n===null||typeof n.executed_at!="string"?[]:[{id:t.id,task_id:typeof n.task_id=="string"?n.task_id:null,executed_at:n.executed_at}]})}function g8(e){return e.flatMap(t=>{let n=t.data;return t.kind!=="evidence"||n===null||typeof n.observed_at!="string"?[]:[{id:t.id,task_id:typeof n.task_id=="string"?n.task_id:null,observed_at:n.observed_at}]})}function rl(e,t){return e.flatMap(n=>n.kind===t&&n.data!==null?[{...n.data,id:n.id,title:n.title??n.data.title,status:n.status??n.data.status,risk:n.risk??n.data.risk,priority:n.priority??n.data.priority,updated_at:n.updated_at}]:[])}function h8(e){return e.flatMap(t=>{if(t.kind!=="decision"||t.data===null)return[];let n=t.data;return n.origin!=="human"&&n.origin!=="agent"||n.scope_type!=="change"&&n.scope_type!=="execution"||typeof n.scope_id!="string"||typeof n.created_at!="string"?[]:[{id:t.id,title:t.title??t.id,origin:n.origin,scope_type:n.scope_type,scope_id:n.scope_id,created_at:n.created_at}]})}function yb(e,t){return rs(e.finished_at??e.updated_at,t)}function BP(e,t,n){return rs(t,n)}function rs(e,t){let n=new Date(e).toISOString();return(t.from===null||n>=t.from)&&(t.to===null||n<=t.to)}var JP=O(()=>{"use strict";xc();ri();Ko();eb();Ec();tb();nb();ib();zp();AP();ob();lb();CP();gb();zP();VP();hb();Qc();rb();ib();zp();lb()});async function vb(e,t,n){if(t.version===1)throw new Error("Task detail requires a modern WorkspaceLayout");let i=new ts(e,t),r=new Go(e,t),o=new lo(e,t),{task:a,body:s}=await i.read(n),{change:l}=await r.read(a.change_id),c=l.source.type==="spec"||l.source.type==="prd"?l.source.spec_id:null,u=await Jp(e,[a],g=>r.path(g)),d=await o.list(),_=$p(d),p=d.filter(g=>g.kind!=="interaction"&&(g.origin.type==="task"&&g.origin.task_id===a.id||g.dag.nodes.some(m=>m.task_id===a.id))).map(g=>g.id).sort();return{task:{...a,attempt_count:a.attempt_count??null,artifact_path:i.path(a.id),progress:Fp(a.status),spec_id:c,execution_started:_.has(a.id),execution_ids:p,execution_count:p.length,test_count:u.get(a.id)??0},body:s,artifact_path:i.path(a.id)}}async function bb(e,t,n){if(t.version===1)throw new Error("PRD detail requires a modern WorkspaceLayout");let i=new Ho(e,t),{prd:r,body:o}=await i.read(n);return{id:r.id,title:r.title,body:o,artifact_path:i.path(r.id)}}async function Sb(e,t,n){if(t.version===1)throw new Error("SPEC detail requires a modern WorkspaceLayout");let i=new Jo(e,t),{spec:r,body:o}=await i.read(n);return{id:r.id,title:r.title,body:o,artifact_path:i.path(r.id)}}var GP=O(()=>{"use strict";Ko();eb();tb();hb();Qc()});var KP={};vS(KP,{aggregateOverviewRunMetrics:()=>mb,aggregateTopTasks:()=>UP,buildOperationsProjection:()=>il,buildQuickOperationsProjection:()=>nl,coverageFromRuns:()=>d8,createDescendantQueries:()=>hP,deliveredMacroCounts:()=>HP,effectiveOperationsDurationMs:()=>kP,estimatedTokenDurationMs:()=>NP,hybridDailyDuration:()=>Yo,hybridLegacyDurationMetric:()=>fb,latestObservedSourceTiming:()=>Mp,macroInWindow:()=>l8,manifestDailyPeriods:()=>o8,normalizeDailyPeriods:()=>db,normalizeTokenBackedDailyDuration:()=>PP,observedExecutionElapsedMs:()=>xi,observedMacroRunTelemetry:()=>cb,observedSourceTiming:()=>Lp,overviewMetricTotals:()=>ZP,projectExecutionDurations:()=>oi,readPrdDetail:()=>bb,readSpecDetail:()=>Sb,readTaskDetail:()=>vb,recalculateOperationsRunSummary:()=>Vp,rootExecutionDurationByDay:()=>el,summaryTopTasks:()=>c8,taskCountsInWindow:()=>r8,withExecutionDurations:()=>n8});var ea=O(()=>{"use strict";Ec();JP();_b();gb();GP()});var wQ={};vS(wQ,{SqliteReadModelFileSystem:()=>ct,app:()=>SQ,createDashboardApp:()=>yS,dashboardWorkspaceKey:()=>nm,defaultDashboardApp:()=>hS,githubRepositoryFromRemote:()=>em,manifestRun:()=>Ob,mergeManifestRuns:()=>ol,openWorkIds:()=>aC,projectAllTimeTopTasks:()=>Qp,projectionPeriodFilter:()=>Et,rebuildSqliteReadModel:()=>_l,reconciliationNeedsRefresh:()=>cM,reconciliationResult:()=>Lb,validateSqliteReadModelSchema:()=>na});module.exports=ZM(wQ);var jM=require("node:crypto"),gl=require("node:path");var SS="x-hono-already-sent";var El=require("node:http"),_i=require("node:http2"),Om=require("node:stream");var kS=e=>((...t)=>{if(typeof t[0]=="function"){let[n,i]=t;return async function(o,a){let s=await n(o),l=await e(o,s,i);if(l)return l;await a()}}else{let[n,i,r]=t;return(async()=>{let o=await e(n,i,r);if(!o)throw new Error("Failed to upgrade WebSocket");return o})()}});var Kn=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},HM=/^\/[!#$&-;=?-\[\]_a-z~]*$/,JM=/\/\.\.?(?:[/?#]|$)/,GM=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,KM=(e,t,n)=>{let i=`${e}://${t}${n}`;if(GM.test(t)){if(n.length===0)return i+"/";if(n.charCodeAt(0)!==47)throw new Kn("Invalid URL");return!HM.test(n)||JM.test(n)?new URL(i).href:i}else{let r=new URL(i);if(r.hostname.length!==t.length&&r.hostname!==(t.includes(":")?t.replace(/:\d+$/,""):t).toLowerCase())throw new Kn("Invalid host header");return r.href}},XM=e=>e instanceof Kn?e:new Kn(e.message,{cause:e}),YM=global.Request,oa=class extends YM{constructor(e,t){if(typeof e=="object"&&$i in e){let n=t!==void 0&&"body"in t&&t.body!=null;if(e[pi]&&!n)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[$i]()}typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},CS=e=>{let t=[],n=e.rawHeaders;for(let i=0,r=n.length;i<r;i+=2){let o=n[i];o.charCodeAt(0)!==58&&t.push([o,n[i+1]])}return new Headers(t)},IS=Symbol("wrapBodyStream"),QM=new Set(["latin1","binary","hex","base64","base64url"]),eD=e=>e===null||QM.has(e),Rm=Symbol("bodyBufferedBeforeDisconnect"),Cm=Symbol("bodyBufferedLengthBeforeDisconnect"),NS=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),Mm=e=>!(e instanceof _i.Http2ServerRequest)&&!!e.complete&&!!e.readableAborted&&typeof e.read=="function"&&eD(e.readableEncoding),wS=e=>{if(e.readableDidRead||!Mm(e))return;let t=e;t[Cm]??=e.readableLength},bl=(e,t)=>{if(e.readableDidRead&&!t||!Mm(e))return;let n=e;if(n[Rm]!==void 0)return n[Rm];let i,r=e.errored;if(r&&r.code!=="ECONNRESET")i=r;else if(n[Cm]!==void 0&&e.readableLength!==n[Cm])i=Sl();else{let o=t??[],a=e.read();a!==null&&o.push(NS(a,e.readableEncoding));let s=o.length===1?o[0]:Buffer.concat(o);i=s;let l=e.headers["content-length"];if(typeof l=="string"&&/^\d+$/.test(l)){let c=Number(l);Number.isSafeInteger(c)&&s.length!==c&&(i=Sl())}}return n[Rm]=i,i},ES=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},tD=(e,t,n,i,r)=>{let o={method:e,headers:n,signal:r.signal};if(e==="TRACE"){o.method="GET";let a=new oa(t,o);return Object.defineProperty(a,"method",{get(){return"TRACE"}}),a}if(!(e==="GET"||e==="HEAD"))if("rawBody"in i&&i.rawBody instanceof Buffer)o.body=new ReadableStream({start(a){a.enqueue(i.rawBody),a.close()}});else if(i[IS]){let a;o.body=new ReadableStream({async pull(s){try{if(!a){let u=bl(i);if(u!==void 0){ES(s,u);return}}a||=Om.Readable.toWeb(i).getReader();let{done:l,value:c}=await a.read();l?s.close():s.enqueue(c)}catch(l){s.error(l)}}})}else{let a=bl(i);a!==void 0?o.body=new ReadableStream({start(s){ES(s,a)}}):o.body=Om.Readable.toWeb(i)}return new oa(t,o)},$i=Symbol("getRequestCache"),ui=Symbol("requestCache"),aa=Symbol("incomingKey"),fs=Symbol("urlKey"),PS=Symbol("methodKey"),$S=Symbol("headersKey"),ps=Symbol("abortControllerKey"),Im=Symbol("getAbortController"),Nm=Symbol("abortRequest"),Pi=Symbol("bodyBuffer"),vl=Symbol("bodyReadPromise"),pi=Symbol("bodyConsumedDirectly"),AS=Symbol("bodyLockReader"),ms=Symbol("abortReason"),Sl=()=>new TypeError("Body is unusable"),gs=()=>Promise.reject(Sl()),nD=new TextDecoder,rD=e=>{if(e[pi])return gs();e[pi]=!0},iD=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),oD=e=>(e[$S]||=CS(e[aa])).get("content-type")||"",aD=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,sD=e=>{if(typeof e!="string"||e.length===0)return"GET";switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return e}let t=e.toUpperCase();switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return t;default:return e}},cD=e=>{if(!aD.test(e))return new TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t==="CONNECT"||t==="TRACK"||t==="TRACE"&&e!=="TRACE")return new TypeError(`'${e}' HTTP method is unsupported.`)},Dm=(e,t,n)=>{if(e[pi])return gs();let i=e.method;if(i==="GET"||i==="HEAD")return e[$i]()[t]();let r=cD(i);if(r)return Promise.reject(r);if(e[ui]&&i!=="TRACE")return e[ui][t]();let o=rD(e);if(o)return o;let a=lD(e);if(a){let s=Promise.resolve(n(a,e));return e[Pi]=void 0,s}return uD(e).then(s=>{let l=n(s,e);return e[Pi]=void 0,l})},lD=e=>{let t=e[aa];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},TS=(e,t)=>{if(t.errored)return t.errored;let n=e[ms];return n!==void 0?n instanceof Error?n:new Error(String(n)):new Error("Client connection prematurely closed.")},uD=e=>{if(e[Pi])return Promise.resolve(e[Pi]);if(e[vl])return e[vl];let t=e[aa];if(t.readableDidRead)return gs();let n=bl(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[Pi]=n,Promise.resolve(n));let i=new Promise((r,o)=>{let a=[],s=!1,l=m=>{s||(s=!0,g(),m())},c=m=>{let f=t.errored??m;return!Mm(t)||f&&f.code!=="ECONNRESET"?!1:(l(()=>{let v=bl(t,a);v instanceof Error?o(v):v===void 0?o(m??TS(e,t)):(e[Pi]=v,r(v))}),!0)},u=m=>{a.push(NS(m,t.readableEncoding))},d=()=>{l(()=>{let m=a.length===1?a[0]:Buffer.concat(a);e[Pi]=m,r(m)})},_=m=>{c(m)||l(()=>{o(m)})},p=()=>{if(t.readableEnded){d();return}c()||l(()=>{o(TS(e,t))})},g=()=>{t.off("data",u),t.off("end",d),t.off("error",_),t.off("close",p),e[vl]=void 0};t.on("data",u),t.on("end",d),t.on("error",_),t.on("close",p),queueMicrotask(()=>{s||(t.readableEnded?d():t.errored?_(t.errored):t.destroyed&&p())})});return e[vl]=i,i},Yn={get method(){return this[PS]},get url(){return this[fs]},get headers(){return this[$S]||=CS(this[aa])},[Nm](e){this[ms]===void 0&&(this[ms]=e);let t=this[ps];t&&!t.signal.aborted&&t.abort(e)},[Im](){return this[ps]||=new AbortController,this[ms]!==void 0&&!this[ps].signal.aborted&&this[ps].abort(this[ms]),this[ps]},[$i](){let e=this[Im]();if(this[ui])return this[ui];let t=this.method;if(this[pi]&&!(t==="GET"||t==="HEAD")){this[Pi]=void 0;let n={method:t==="TRACE"?"GET":t,headers:this.headers,signal:e.signal};t!=="TRACE"&&(n.body=new ReadableStream({start(r){r.close()}}),n.duplex="half");let i=new oa(this[fs],n);return t==="TRACE"&&Object.defineProperty(i,"method",{get(){return"TRACE"}}),this[ui]=i}return this[ui]=tD(this.method,this[fs],this.headers,this[aa],e)},get body(){if(!this[pi])return this[$i]().body;let e=this[$i]();return!this[AS]&&e.body&&(this[AS]=e.body.getReader()),e.body},get bodyUsed(){return this[pi]?!0:this[ui]?this[ui].bodyUsed:!1}};Object.defineProperty(Yn,"signal",{get(){return this[Im]().signal}});["cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(Yn,e,{get(){return this[$i]()[e]}})});["clone","formData"].forEach(e=>{Object.defineProperty(Yn,e,{value:function(){if(this[pi]){if(e==="clone")throw Sl();return gs()}return this[$i]()[e]()}})});Object.defineProperty(Yn,"text",{value:function(){return Dm(this,"text",e=>nD.decode(e))}});Object.defineProperty(Yn,"arrayBuffer",{value:function(){return Dm(this,"arrayBuffer",e=>iD(e))}});Object.defineProperty(Yn,"blob",{value:function(){return Dm(this,"blob",(e,t)=>{let n=oD(t),i=n?{headers:{"content-type":n}}:void 0;return new Response(e,i).blob()})}});Object.defineProperty(Yn,"json",{value:function(){return this[pi]?gs():this.text().then(JSON.parse)}});Object.defineProperty(Yn,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[ui]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Yn,oa.prototype);var dD=(e,t)=>{let n=Object.create(Yn);n[aa]=e,n[PS]=sD(e.method);let i=e.url||"";if(i[0]!=="/"&&(i.startsWith("http://")||i.startsWith("https://"))){if(e instanceof _i.Http2ServerRequest)throw new Kn("Absolute URL for :path is not allowed in HTTP/2");try{n[fs]=new URL(i).href}catch(a){throw new Kn("Invalid absolute URL",{cause:a})}return n}let r=(e instanceof _i.Http2ServerRequest?e.authority:e.headers.host)||t;if(!r)throw new Kn("Missing host header");let o;if(e instanceof _i.Http2ServerRequest){if(o=e.scheme,!(o==="http"||o==="https"))throw new Kn("Unsupported scheme")}else o=e.socket&&e.socket.encrypted?"https":"http";try{n[fs]=KM(o,r,i)}catch(a){throw a instanceof Kn?a:new Kn("Invalid URL",{cause:a})}return n},Ni="text/plain; charset=UTF-8",Pm=Symbol("responseCache"),ia=Symbol("getResponseCache"),di=Symbol("cache"),jm=global.Response,Xn=class LS{#e;#t;[ia](){let t=this[di],n=t&&t[2]instanceof Headers?t[2]:void 0;return delete this[di],this[Pm]||=new jm(this.#e,n?{status:this.#t?.status,statusText:this.#t?.statusText,headers:n}:this.#t)}constructor(t,n){let i;if(this.#e=t,n instanceof LS){let r=n[Pm];if(r){this.#t=r,this[ia]();return}else this.#t=n.#t,i=new Headers(n.headers)}else this.#t=n;(t==null||typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[di]=[n?.status||200,t??null,i||n?.headers])}get headers(){let t=this[di];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||(t[1]===null?void 0:{"content-type":Ni}))),t[2]):this[ia]().headers}get status(){return this[di]?.[0]??this[ia]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(Xn.prototype,e,{get(){return this[ia]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(Xn.prototype,e,{value:function(){return this[ia]()[e]()}})});Object.defineProperty(Xn.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Pm]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Xn,jm);Object.setPrototypeOf(Xn.prototype,jm.prototype);var _D=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,pD=e=>e instanceof URL?e.href:_D.test(e)?e:new URL(e).href,mD=new Set([301,302,303,307,308]);Object.defineProperty(Xn,"redirect",{value:function(t,n=302){if(!mD.has(n))throw new RangeError("Invalid status code");return new Xn(null,{status:n,headers:{location:pD(t)}})},writable:!0,configurable:!0});Object.defineProperty(Xn,"json",{value:function(t,n){let i=JSON.stringify(t);if(i===void 0)throw new TypeError("The data is not JSON serializable");let r=n?.headers,o;return r?(o=new Headers(r),o.has("content-type")||o.set("content-type","application/json")):o={"content-type":"application/json"},new Xn(i,{status:n?.status??200,statusText:n?.statusText,headers:o})},writable:!0,configurable:!0});async function fD(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function MS(e,t,n){let i=s=>{e.cancel(s).catch(()=>{})};return t.on("close",i),t.on("error",i),(n??e.read()).then(a,r),e.closed.finally(()=>{t.off("close",i),t.off("error",i)});function r(s){s&&t.destroy(s)}function o(){e.read().then(a,r)}function a({done:s,value:l}){try{if(s)t.end();else if(!t.write(l))t.once("drain",o);else return e.read().then(a,r)}catch(c){r(c)}}}function xS(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:MS(e.getReader(),t)}var $m=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has("set-cookie")){let i=[];for(let[r,o]of e)r==="set-cookie"?i.push(o):n[r]=o;i.length>0&&(n["set-cookie"]=i)}else for(let[i,r]of e)n[i]=r;return t&&(n["content-type"]??=t),n},kl=Symbol("outgoingEnded"),RS=Symbol("incomingDraining"),gD=500,hD=64*1024*1024,DS=e=>{let t=e;if(e.destroyed||t[RS])return;if(t[RS]=!0,e instanceof _i.Http2ServerRequest){try{e.stream?.close?.(_i.constants.NGHTTP2_NO_ERROR)}catch{}return}let n=0,i=()=>{clearTimeout(o),e.off("data",a),e.off("end",i),e.off("error",i)},r=()=>{i();let s=e.socket;s&&!s.destroyed&&s.destroySoon()},o=setTimeout(r,gD);o.unref?.();let a=s=>{n+=s.length,n>hD&&r()};e.on("data",a),e.on("end",i),e.on("error",i),e.resume()},yD=(e,t,n,i)=>()=>{t.errored?(wS(t),e[Nm](t.errored.toString())):n.writableFinished||(wS(t),e[Nm]("Client connection prematurely closed.")),i&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{DS(t)})})},vD=e=>{if(!(di in e))return!1;let t=e[di][1];return t===null||typeof t=="string"||t instanceof Uint8Array},bD=()=>new Response(null,{status:400}),jS=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),wl=(e,t)=>{let n=e instanceof Error?e:new Error("unknown error",{cause:e});n.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${n.message}`),t.destroy(n))},Lm=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},US=async(e,t)=>{let[n,i,r]=e[di];if(!r){i===null?(t.writeHead(n),t.end()):typeof i=="string"?(t.writeHead(n,{"Content-Type":Ni,"Content-Length":Buffer.byteLength(i)}),t.end(i)):i instanceof Uint8Array?(t.writeHead(n,{"Content-Type":Ni,"Content-Length":i.byteLength}),t.end(i)):i instanceof Blob?(t.writeHead(n,{"Content-Type":Ni,"Content-Length":i.size}),t.end(new Uint8Array(await i.arrayBuffer()))):(t.writeHead(n,{"Content-Type":Ni}),Lm(t),await xS(i,t)?.catch(a=>wl(a,t))),t[kl]?.();return}let o=!1;if(r instanceof Headers)o=r.has("content-length"),r=$m(r,i===null?void 0:Ni);else if(Array.isArray(r)){let a=new Headers(r);o=a.has("content-length"),r=$m(a,i===null?void 0:Ni)}else for(let a in r)if(a.length===14&&a.toLowerCase()==="content-length"){o=!0;break}o||(typeof i=="string"?r["Content-Length"]=Buffer.byteLength(i):i instanceof Uint8Array?r["Content-Length"]=i.byteLength:i instanceof Blob&&(r["Content-Length"]=i.size)),t.writeHead(n,r),i==null?t.end():typeof i=="string"||i instanceof Uint8Array?t.end(i):i instanceof Blob?t.end(new Uint8Array(await i.arrayBuffer())):(Lm(t),await xS(i,t)?.catch(a=>wl(a,t))),t[kl]?.()},FS=e=>typeof e.then=="function",SD=async(e,t,n={})=>{if(FS(e))if(n.errorHandler)try{e=await e}catch(r){let o=await n.errorHandler(r);if(!o)return;e=o}else e=await e.catch(jS);if(di in e)return US(e,t);let i=$m(e.headers,e.body===null?void 0:Ni);if(e.body){let r=e.body.getReader(),o=[],a=!1,s;if(i["transfer-encoding"]!=="chunked"){let l=2;for(let c=0;c<l;c++){s||=r.read();let u=await fD(s).catch(d=>{console.error(d),a=!0});if(!u){if(c===1){await new Promise(d=>setTimeout(d)),l=3;continue}break}if(s=void 0,u.value&&o.push(u.value),u.done){a=!0;break}}a&&!("content-length"in i)&&(i["content-length"]=o.reduce((c,u)=>c+u.length,0))}t.writeHead(e.status,i),o.forEach(l=>{t.write(l)}),a?t.end():(o.length===0&&Lm(t),await MS(r,t,s))}else i[SS]||(t.writeHead(e.status,i),t.end());t[kl]?.()},kD=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==oa&&(Object.defineProperty(global,"Request",{value:oa}),Object.defineProperty(global,"Response",{value:Xn})),async(i,r)=>{let o,a,s=!1,l=!1,c=()=>{!a||l||(l=!0,r.on("close",yD(a,i,r,s)))};try{if(a=dD(i,t.hostname),s=n&&!(i.method==="GET"||i.method==="HEAD"),s&&(i[IS]=!0,i instanceof _i.Http2ServerRequest&&(r[kl]=()=>{i.readableEnded||setTimeout(()=>{i.readableEnded||setTimeout(()=>{i.destroy(),r.destroy()})})})),o=e(a,{incoming:i,outgoing:r}),!FS(o)&&vD(o))return s&&!i.readableEnded&&r.once("finish",()=>{i.readableEnded||DS(i)}),US(o,r);c()}catch(u){if(o)return wl(u,r);if(t.errorHandler){if(c(),o=await t.errorHandler(a?u:XM(u)),!o)return}else a?o=jS(u):o=bD()}try{return await SD(o,r,t)}catch(u){return wl(u,r)}}},wD=globalThis.CloseEvent??class extends Event{#e;constructor(e,t={}){super(e,t),this.#e=t}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},ED=globalThis.ErrorEvent??class extends Event{#e;constructor(e,t={}){super(e,t),this.#e=t}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},AD=()=>Symbol("connection"),zS=Symbol("CONNECTION_SYMBOL_KEY"),qS=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),TD=new Set(["connection","content-length","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-accept","sec-websocket-extensions","sec-websocket-protocol"]),VS=(e,t)=>{t&&t.forEach((n,i)=>{TD.has(i.toLowerCase())||e.push(`${i}: ${n}`)})},OS=(e,t,n)=>{let i=["Connection: close","Content-Length: 0"];VS(i,n),e.end(`HTTP/1.1 ${t.toString()} ${El.STATUS_CODES[t]??""}\r
|
|
348
348
|
${i.join(`\r
|
|
349
349
|
`)}\r
|
|
350
350
|
\r
|
|
351
|
-
`)},xD=e=>{let t=e.socket.encrypted?"https":"http",n=new URL(e.url??"/",`${t}://${e.headers.host??"localhost"}`),i=new Headers;for(let r in e.headers){let o=e.headers[r];o&&i.append(r,Array.isArray(o)?o[0]:o)}return new Request(n,{headers:i})},RD=e=>{let{server:t,fetchCallback:n,wss:i}=e,r=new Map;i.on("connection",(s,l)=>{let c=r.get(l);c&&(c.resolve(s),r.delete(l))});let o=s=>{let l=r.get(s);l&&(r.delete(s),l.reject(new Error("WebSocket handshake aborted")))},a=(s,l)=>new Promise((c,u)=>{r.set(s,{resolve:c,reject:u,connectionSymbol:l})});t.on("upgrade",async(s,l,c)=>{if(s.headers.upgrade?.toLowerCase()!=="websocket")return;let u={incoming:s,outgoing:void 0,wss:i,[qS]:a},d=400,_;try{let f=await n(xD(s),u);f instanceof Response&&(d=f.status,_=f.headers)}catch{t.listenerCount("upgrade")===1&&OS(l,500);return}let p=r.get(s);if(!p||p.connectionSymbol!==u[zS]){o(s),t.listenerCount("upgrade")===1&&OS(l,d,_);return}let g=f=>{VS(f,_)},m=()=>o(s);l.once("close",m),i.on("headers",g);try{i.handleUpgrade(s,l,c,f=>{l.off("close",m),i.emit("connection",f,s)})}finally{i.off("headers",g)}}),t.on("close",()=>{i.close()})},O8=kS(async(e,t,n)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let i=e.env,r=i[qS];if(!r||!i.incoming)return new Response(null,{status:500});let o=AD();return i[zS]=o,(async()=>{let a;try{a=await r(i.incoming,o)}catch{return}let s=[],l=(d,_)=>{s.push([d,_])};a.on("message",l);let c={binaryType:"arraybuffer",close(d,_){a.close(d,_)},protocol:a.protocol,raw:a,get readyState(){return a.readyState},send(d,_){a.send(d,{compress:_?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),c)}catch(d){(n?.onError??console.error)(d)}let u=(d,_)=>{let p=Array.isArray(d)?d:[d];for(let g of p)try{t?.onMessage?.(new MessageEvent("message",{data:_?g instanceof ArrayBuffer?g:g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength):typeof g=="string"?g:Buffer.from(g).toString("utf-8")}),c)}catch(m){(n?.onError??console.error)(m)}};a.off("message",l);for(let d of s)u(...d);a.on("message",(d,_)=>{u(d,_)}),a.on("close",(d,_)=>{try{t?.onClose?.(new wD("close",{code:d,reason:_.toString()}),c)}catch(p){(n?.onError??console.error)(p)}}),a.on("error",d=>{try{t?.onError?.(new ED("error",{error:d}),c)}catch(_){(n?.onError??console.error)(_)}})})(),new Response}),OD=e=>{let t=e.fetch,n=kD(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),i=(e.createServer||El.createServer)(e.serverOptions||{},n);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw new Error("WebSocket server must be created with { noServer: true } option");RD({server:i,fetchCallback:t,wss:e.websocket.server})}return i},WS=(e,t)=>{let n=OD(e);return n.listen(e?.port??3e3,e.hostname,()=>{let i=n.address();t&&t(i)}),n};var BS=require("node:stream"),ZS=require("node:process"),CD=()=>{let[e,t]=ZS.versions.node.split(".").map(n=>parseInt(n));return e>=23||e===22&&t>=7||e===20&&t>=18},ID=CD(),Um=(e,t=ID)=>{if(t)return BS.Readable.toWeb(e);let n,i=!1,r=()=>{e.off("data",a),e.off("error",s),e.off("end",l),e.off("close",l)},o=c=>{i||(i=!0,r(),c?.())},a=c=>{i||!n||(n.enqueue(c),(n.desiredSize??0)<=0&&e.pause())},s=c=>{o(()=>{n?.error(c)})},l=()=>{o(()=>{n?.close()})};return new ReadableStream({start(c){n=c,e.on("data",a),e.on("error",s),e.on("end",l),e.on("close",l),e.pause()},pull(){i||e.resume()},cancel(){o();let c=()=>{};e.on("error",c),e.once("close",()=>e.off("error",c)),e.destroy()}})};var HS=(e,t=PD)=>{let n=/\.([a-zA-Z0-9]+?)$/,i=e.match(n);if(i)return t[i[1].toLowerCase()]};var ND={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css; charset=utf-8",csv:"text/csv; charset=utf-8",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html; charset=utf-8",html:"text/html; charset=utf-8",ico:"image/x-icon",ics:"text/calendar; charset=utf-8",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript; charset=utf-8",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript; charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml; charset=utf-8",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain; charset=utf-8",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml; charset=utf-8",xml:"application/xml; charset=utf-8",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},PD=ND;var go=require("node:fs"),zm=require("node:path"),$D=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,qm={br:".br",zstd:".zst",gzip:".gz"},LD=Object.keys(qm),Fm=e=>{let t;try{t=(0,go.statSync)(e)}catch{}return t},MD=/^(?:bytes=)?(?!-$)(\d*)-(\d*)$/,DD=e=>{let t=e.match(MD);if(!t)return;let[,n,i]=t;return n===""?{type:"suffix",length:Number(i)}:i===""?{type:"open-ended",start:Number(n)}:{type:"bounded",start:Number(n),end:Number(i)}},jD=(e,t)=>{if(t===0)return;if(e.type==="suffix")return e.length===0?void 0:{start:Math.max(t-e.length,0),end:t-1};let n=e.type==="bounded"?Math.min(e.end,t-1):t-1;if(!(e.start>=t||e.start>n))return{start:e.start,end:n}},UD=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},FD=e=>UD(e,decodeURI),Al=(e={root:""})=>{let t=e.root||"",n=e.path;return t!==""&&!(0,go.existsSync)(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(i,r)=>{if(i.finalized)return r();let o;if(n)o=n;else try{if(o=FD(i.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(o))throw new Error}catch{return await e.onNotFound?.(i.req.path,i),r()}let a=(0,zm.join)(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(o,i):o),s=Fm(a);if(s&&s.isDirectory()){let _=e.index??"index.html";a=(0,zm.join)(a,_),s=Fm(a)}if(!s)return await e.onNotFound?.(a,i),r();let l=HS(a);if(i.header("Content-Type",l||"application/octet-stream"),e.precompressed&&(!l||l==="application/octet-stream"||$D.test(l))){let _=new Set(i.req.header("Accept-Encoding")?.split(",").map(p=>p.trim()));for(let p of LD){if(!_.has(p))continue;let g=Fm(a+qm[p]);if(g){i.header("Content-Encoding",p),i.header("Vary","Accept-Encoding",{append:!0}),s=g,a=a+qm[p];break}}}let c,u=s.size,d=i.req.header("range")||"";if(i.header("Last-Modified",s.mtime.toUTCString()),i.req.method=="HEAD"||i.req.method=="OPTIONS")i.header("Content-Length",u.toString()),i.status(200),c=i.body(null);else if(!d)i.header("Content-Length",u.toString()),c=i.body(Um((0,go.createReadStream)(a)),200);else{i.header("Accept-Ranges","bytes");let _=jD(DD(d)??{type:"open-ended",start:0},u);if(!_)i.header("Content-Range",`bytes */${u}`),c=i.body(null,416);else{let{start:p,end:g}=_,m=g-p+1,f=(0,go.createReadStream)(a,{start:p,end:g});i.header("Content-Length",m.toString()),i.header("Content-Range",`bytes ${p}-${g}/${u}`),c=i.body(Um(f),206)}}return await e.onFound?.(a,i),c}};qe();var zh=(e,t,n)=>(i,r)=>{let o=-1;return a(0);async function a(s){if(s<=o)throw new Error("next() called multiple times");o=s;let l,c=!1,u;if(e[s]?(u=e[s][0][0],i.req.routeIndex=s):u=s===e.length&&r||void 0,u)try{l=await u(i,()=>a(s+1))}catch(d){if(d instanceof Error&&t)i.error=d,l=await t(d,i),c=!0;else throw d}else i.finalized===!1&&n&&(l=await n(i));return l&&(i.finalized===!1||c)&&(i.res=l),i}};var HR=Symbol();var JR=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,i=>i.toLowerCase())}}).formData();var GR=32,PX=1e4,h_=e=>"headers"in e,YR=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=(h_(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return a==="multipart/form-data"||a==="application/x-www-form-urlencoded"?$X(e,{all:n,dot:i}):{}};async function $X(e,t){if(!h_(e)&&e.bodyCache.formData)return KR(await e.bodyCache.formData,t);let n=h_(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),r=JR(i,n.get("Content-Type")||"");h_(e)||(e.bodyCache.formData=r);let o=await r;return o?KR(o,t):{}}function KR(e,t){let n=Object.create(null),i={count:0};return e.forEach((r,o)=>{t.all||o.endsWith("[]")?LX(n,o,r):n[o]=r}),t.dot&&Object.entries(n).forEach(([r,o])=>{r.includes(".")&&(MX(n,r,o,i),delete n[r])}),n}var LX=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n},MX=(e,t,n,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let r=e,o=t.split(".",GR+2);o.length>GR+1&&XR(),o.forEach((a,s)=>{s===o.length-1?r[a]=n:((!r[a]||typeof r[a]!="object"||Array.isArray(r[a])||r[a]instanceof File)&&(i.count++>=PX&&XR(),r[a]=Object.create(null)),r=r[a])})},XR=()=>{throw new Error("Nesting limit exceeded")};var Vh=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},QR=e=>{let{groups:t,path:n}=DX(e),i=Vh(n);return jX(i,t)},DX=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,i)=>{let r=`@${i}`;return t.push([r,n]),r}),{groups:t,path:e}},jX=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[i]=t[n];for(let r=e.length-1;r>=0;r--)if(e[r].includes(i)){e[r]=e[r].replace(i,t[n][1]);break}}return e},y_={},eO=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let i=`${e}#${t}`;return y_[i]||(n[2]?y_[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:y_[i]=[e,n[1],!0]),y_[i]}return null},tO=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},UX=e=>tO(e,decodeURI),Wh=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),i=n;for(;i<t.length;i++){let r=t.charCodeAt(i);if(r===37){let o=t.indexOf("?",i),a=t.indexOf("#",i),s=o===-1?a===-1?void 0:a:a===-1?o:Math.min(o,a),l=t.slice(n,s);return UX(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(r===63||r===35)break}return t.slice(n,i)};var nO=e=>{let t=Wh(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Gi=(e,t,...n)=>(n.length&&(t=Gi(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),v_=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],i="";return t.forEach(r=>{if(r!==""&&!/\:/.test(r))i+="/"+r;else if(/\:/.test(r))if(r.charCodeAt(r.length-1)===63){n.length===0&&i===""?n.push("/"):n.push(i);let o=r.slice(0,-1);i+="/"+o,n.push(i)}else i+="/"+r}),n.filter((r,o,a)=>a.indexOf(r)===o)},Ca=e=>e.indexOf("%")!==-1?tO(e,FX):e,qh=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Ca(e)),rO=(e,t,n)=>{let i=e.indexOf("#",8);i!==-1&&(e=e.slice(0,i));let r;if(!n&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let s=e.indexOf("?",8);if(s===-1)return;for(e.startsWith(t,s+1)||(s=e.indexOf(`&${t}`,s+1));s!==-1;){let l=e.charCodeAt(s+t.length+1);if(l===61){let c=s+t.length+2,u=e.indexOf("&",c);return qh(e.slice(c,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";s=e.indexOf(`&${t}`,s+1)}if(r=/[%+]/.test(e),!r)return}let o=Object.create(null);r??=/[%+]/.test(e);let a=e.indexOf("?",8);for(;a!==-1;){let s=e.indexOf("&",a+1),l=e.indexOf("=",a);l>s&&s!==-1&&(l=-1);let c=e.slice(a+1,l===-1?s===-1?void 0:s:l);if(r&&(c=qh(c)),a=s,c==="")continue;let u;l===-1?u="":(u=e.slice(l+1,s===-1?void 0:s),r&&(u=qh(u))),n?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(u)):o[c]??=u}return t?o[t]:o},iO=rO,oO=(e,t)=>rO(e,t,!0),FX=decodeURIComponent;var aO=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#o()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#r(t);return n&&Ca(n)}#o(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let i=this.#r(this.#t[0][this.routeIndex][1][n]);i!==void 0&&(e[n]=Ca(i))}return e}#r(e){return this.#t[1]?this.#t[1][e]:e}query(e){return iO(this.url,e)}queries(e){return oO(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((n,i)=>{t[i]=n}),t}async parseBody(e){return YR(this,e)}#i=e=>{let{bodyCache:t,raw:n}=this,i=t[e];if(i)return i;for(let r in t)return t[r].then(o=>(r==="json"&&(o=JSON.stringify(o)),new Response(o)[e]()));return t[e]=n[e]()};json(){return this.#i("text").then(e=>JSON.parse(e))}text(){return this.#i("text")}arrayBuffer(){return this.#i("arrayBuffer")}bytes(){return this.#i("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#i("blob")}formData(){return this.#i("formData")}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[HR](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};var b_={Stringify:1,BeforeStream:2,Stream:3},zX=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var _c=async(e,t,n,i,r)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);r?r[0]+=e:r=[e];let a=Promise.all(o.map(s=>s({phase:t,buffer:r,context:i}))).then(s=>Promise.all(s.filter(Boolean).map(l=>_c(l,t,!1,i,r))).then(()=>r[0]));return n?zX(await a,o):a};var sO="text/plain; charset=UTF-8",Bh=(e,t)=>({"Content-Type":e,...t}),pc=(e,t)=>new Response(e,t),Zh=class{#e;#t;env={};#n;finalized=!1;error;#o;#r;#i;#u;#c;#l;#s;#d;#_;constructor(e,t){this.#e=e,t&&(this.#r=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#_=t.path,this.#d=t.matchResult)}get req(){return this.#t??=new aO(this.#e,this.#_,this.#d),this.#t}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#i||=pc(null,{headers:this.#s??=new Headers})}set res(e){if(this.#i&&e){e=pc(e.body,e);for(let[t,n]of this.#i.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let i=this.#i.headers.getSetCookie();e.headers.delete("set-cookie");for(let r of i)e.headers.append("set-cookie",r)}else e.headers.set(t,n)}this.#i=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,n)=>{this.finalized&&(this.#i=pc(this.#i.body,this.#i));let i=this.#i?this.#i.headers:this.#s??=new Headers;t===void 0?i.delete(e):n?.append?i.append(e,t):i.set(e,t)};status=e=>{this.#o=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#a(e,t,n){let i=this.#i?new Headers(this.#i.headers):this.#s;if(typeof t=="object"&&t.headers){i??=new Headers;for(let[o,a]of new Headers(t.headers))o==="set-cookie"?i.append(o,a):i.set(o,a)}if(n){if(!i){let o=0;for(let a in n)if(++o>1||typeof n[a]!="string"){i=new Headers;break}}if(i)for(let o in n){let a=n[o];if(typeof a=="string")i.set(o,a);else{i.delete(o);for(let s of a)i.append(o,s)}}}let r=typeof t=="number"?t:t?.status??this.#o;return pc(e,{status:r,headers:i??n})}newResponse=(...e)=>this.#a(...e);body=(e,t,n)=>this.#a(e,t,n);text=(e,t,n)=>!this.#s&&!this.#o&&!t&&!n&&!this.finalized?new Response(e):this.#a(e,t,Bh(sO,n));json=(e,t,n)=>this.#a(JSON.stringify(e),t,Bh("application/json",n));html=(e,t,n)=>{let i=r=>this.#a(r,t,Bh("text/html; charset=UTF-8",n));return typeof e=="object"?_c(e,b_.Stringify,!1,{}).then(i):i(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>pc(),this.#l(this))};var Vt="ALL",cO="all",lO=["get","post","put","delete","options","patch","query"],S_="Can not add a route since the matcher is already built.",k_=class extends Error{};var uO="__COMPOSED_HANDLER";var qX=e=>e.text("404 Not Found",404),dO=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},_O=class pO{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...lO,cO].forEach(o=>{this[o]=(a,...s)=>{let l=o.toUpperCase();return typeof a=="string"?this.#e=a:this.#o(l,this.#e,a),s.forEach(c=>{this.#o(l,this.#e,c)}),this}}),this.on=(o,a,...s)=>{for(let l of[a].flat()){this.#e=l;for(let c of[o].flat()){let u=c.toUpperCase();for(let d of s)this.#o(u,this.#e,d)}}return this},this.use=(o,...a)=>(typeof o=="string"?this.#e=o:(this.#e="*",a.unshift(o)),a.forEach(s=>{this.#o(Vt,this.#e,s)}),this);let{strict:i,...r}=t;Object.assign(this,r),this.getPath=i??!0?t.getPath??Wh:nO}#t(){let t=new pO({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=qX;errorHandler=dO;route(t,n){let i=this.basePath(t);return n.routes.map(r=>{let o;n.errorHandler===dO?o=r.handler:(o=async(a,s)=>(await zh([],n.errorHandler)(a,()=>r.handler(a,s))).res,o[uO]=r.handler),i.#o(r.method,r.path,o,r.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=Gi(this._basePath,t),n}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#n=t,this);mount(t,n,i){let r,o;i&&(typeof i=="function"?o=i:(o=i.optionHandler,i.replaceRequest===!1?r=l=>l:r=i.replaceRequest));let a=o?l=>{let c=o(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx}catch{}return[l.env,c]};r||=(()=>{let l=Gi(this._basePath,t),c=l==="/"?0:l.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(c)||"/",new Request(d,u)}})();let s=async(l,c)=>{let u=await n(r(l.req.raw),...a(l));if(u)return u;await c()};return this.#o(Vt,Gi(t,"*"),s),this}#o(t,n,i,r){n=Gi(this._basePath,n);let o={basePath:r!==void 0?Gi(this._basePath,r):this._basePath,path:n,method:t,handler:i};this.router.add(t,n,[i,o]),this.routes.push(o)}#r(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#i(t,n,i,r){if(r==="HEAD")return(async()=>new Response(null,await this.#i(t,n,i,"GET")))();let o=this.getPath(t,{env:i}),a=this.router.match(r,o),s=new Zh(t,{path:o,matchResult:a,env:i,executionCtx:n,notFoundHandler:this.#n});if(a[0].length===1){let c;try{c=a[0][0][0][0](s,async()=>{s.res=await this.#n(s)})}catch(u){return this.#r(u,s)}return c instanceof Promise?c.then(u=>u||(s.finalized?s.res:this.#n(s))).catch(u=>this.#r(u,s)):c??this.#n(s)}let l=zh(a[0],this.errorHandler,this.#n);return(async()=>{try{let c=await l(s);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#r(c,s)}})()}fetch=(t,...n)=>this.#i(t,n[1],n[0],t.method);request=(t,n,i,r)=>t instanceof Request?this.fetch(n?new Request(t,n):t,i,r):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Gi("/",t)}`,n),i,r));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#i(t.request,t,void 0,t.request.method))})}};var Lt=()=>Object.create(null);var w_=[];function Hh(e,t){let n=this.buildAllMatchers(),i=((r,o)=>{let a=n[r]||n[Vt],s=a[2][o];if(s)return s;let l=o.match(a[0]);if(!l)return[[],w_];let c=l.indexOf("",1);return[a[1][c],l]});return this.match=i,i(e,t)}var Ia="[^/]+",Xi=".*",ki="(?:|/.*)",Ki=Symbol(),mO=new Set(".\\+*[^]$()");function VX(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===Xi||e===ki?t===ki?-1:1:t===Xi||t===ki?-1:e===Ia?1:t===Ia?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var fO=class Jh{#e;#t;#n=Lt();insert(t,n,i,r,o){let a=this;for(let s=0,l=t.length;s<l;s++){let c=t[s],u=c.length===1?c==="*"?s===l-1?["","",Xi]:["","",Ia]:null:c==="/*"?["","",ki]:c.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let _=u[1],p=u[2]||Ia;if(_&&u[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))||p.length===1&&mO.has(p)))throw Ki;if(d=a.#n[p],!d){if(p!==Xi&&p!==ki){for(let g in a.#n)if((p.length>1||g.length>1)&&g!==Xi&&g!==ki)throw Ki}d=a.#n[p]=new Jh}_!==""&&(d.#t??=r.varIndex++,i.push([_,d.#t]))}else if(d=a.#n[c],!d){for(let _ in a.#n)if(_.length>1&&_!==Xi&&_!==ki)throw Ki;d=a.#n[c]=new Jh}a=d}if(a.#e!==void 0)throw Ki;a.#e=o?-1:n}buildRegExpStr(){let n=Object.keys(this.#n).sort(VX).map(i=>{let r=this.#n[i],o=r.buildRegExpStr();return o===""?"":(typeof r.#t=="number"?`(${i})@${r.#t}`:mO.has(i)?`\\${i}`:i)+o}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&n.unshift(`#${this.#e}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var Gh=class{#e={varIndex:0};#t=new fO;#n=0;paths=Lt();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let n=[],i=[],r=e;for(let a=0;;){let s=!1;if(r=r.replace(/\{[^}]+\}/g,l=>{let c=`@\\${a}`;return i[a]=[c,l],a++,s=!0,c}),!s)break}let o=r.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=i.length-1;a>=0;a--){let[s]=i[a];for(let l=o.length-1;l>=0;l--)if(o[l].indexOf(s)!==-1){o[l]=o[l].replace(s,i[a][1]);break}}this.#t.insert(o,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],i=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(r,o,a)=>o!==void 0?(n[++t]=Number(o),"$()"):(a!==void 0&&(i[Number(a)]=++t),"")),[new RegExp(`^${e}`),n,i]}};var gO=Lt();function hO(e){return gO[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,n)=>n?`\\${n}`:t==="/*"?ki:t==="*"?Xi:`/:${Ia}`)}$`)}function E_(e,t){for(let n of Object.keys(e).sort((i,r)=>r.length-i.length))if(hO(n).test(t))return[...e[n]]}var A_=class{name="RegExpRouter";#e;#t;#n;constructor(){this.#e={[Vt]:Lt()},this.#t={[Vt]:Lt()},this.#n={[Vt]:new Gh}}#o(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===Ki?new k_(t):n}}add(e,t,n){let i=this.#e,r=this.#t;if(!i)throw new Error(S_);if(!i[e]){this.#n[e]=new Gh;for(let s of[i,r]){s[e]=Lt();for(let l in s[Vt])s[e][l]=[...s[Vt][l]],this.#o(e,l)}}t==="/*"&&(t="*");let o=e===Vt?Object.keys(i):[e];if(/\*$/.test(t)){let s=hO(t);for(let l of o)i[l][t]||(this.#o(l,t),i[l][t]=E_(i[l],t)||E_(i[Vt],t)||[]);for(let l of[i,r])for(let c of o)for(let u in l[c])s.test(u)&&l[c][u].push([n,t]);return}let a=v_(t)||[t];for(let s of a)for(let l of o)r[l][s]||(this.#o(l,s),r[l][s]=E_(i[l],s)||E_(i[Vt],s)||[]),r[l][s].push([n,s])}match=Hh;buildAllMatchers(){let e=Lt();for(let t of Object.keys(this.#t))e[t]=this.#r(t);return this.#e=this.#t=this.#n=void 0,gO=Lt(),e}#r(e){let t=this.#e[e],n=this.#t[e],i=this.#n[e],r=Lt(),o=[],[a,s,l]=i.buildRegExp();for(let c of[t,n])for(let u in c){let d=c[u],_=i.paths[u];if(!_){r[u]=[d.map(([p])=>[p,Lt()]),w_];continue}o[_[0]]=d.map(([p,g])=>[p,i.paths[g][1].reduceRight((m,[f],v)=>(m[f]=l[_[1][v][1]],m),Lt())])}return[a,s.map(c=>o[c]),r]}};var Kh=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw new Error(S_);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw new Error("Fatal error");let n=this.#e,i=this.#t,r=n.length,o=0,a;for(;o<r;o++){let s=n[o];try{for(let l=0,c=i.length;l<c;l++)s.add(...i[l]);a=s.match(e,t)}catch(l){if(l instanceof k_)continue;throw l}this.match=s.match.bind(s),this.#e=[s],this.#t=void 0;break}if(o===r)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var Xh=Lt(),WX=0,yO=class vO{#e=[];#t=Lt();#n=[];#o;#r=Xh;insert(t,n,i){let r=this,o=QR(n),a=new Set,s=0;for(let l of o){let c=o[++s],u=eO(l,c)||(c===void 0&&l&&l.indexOf("*")===l.length-1?l:null),d=Array.isArray(u),_=d?u[0]:u||l,p=r.#t[_]||=new vO;u&&!p.#o&&(p.#o=u,r.#n.push(p)),r=p,d&&a.add(u[1])}r.#e.push({[t]:{handler:i,possibleKeys:[...a],score:++WX}})}#i(t,n,i,r,o){for(let a=0,s=n.#e.length;a<s;a++){let l=n.#e[a],c=l[i]||l[Vt];if(c){c.params=Lt(),t.push(c);for(let u=0,d=c.possibleKeys.length;u<d;u++){let _=c.possibleKeys[u];c.params[_]=o?.[_]&&!u?o[_]:r[_]??o?.[_]}}}}search(t,n){let i=[];this.#r=Xh;let o=[this],a=Vh(n),s=[],l=a.length,c=null;for(let u=0;u<l;u++){let d=a[u],_=u===l-1,p=[];for(let m=0,f=o.length;m<f;m++){let v=o[m],S=v.#t[d];S&&(S.#r=v.#r,_?(S.#t["*"]&&this.#i(i,S.#t["*"],t,v.#r),this.#i(i,S,t,v.#r)):p.push(S));for(let b of v.#n){let h=b.#o,k=v.#r===Xh?{}:{...v.#r};if(typeof h=="string"){(h==="*"||d.startsWith(h.slice(0,-1)))&&(this.#i(i,b,t,v.#r),h==="*"&&(b.#r=k,p.push(b)));continue}let[,P,U]=h;if(!(!d&&U===!0)){if(U!==!0){if(!c){c=[];let z=n[0]==="/"?1:0;for(let R=0;R<l;R++)c[R]=z,z+=a[R].length+1}let $=n.slice(c[u]),B=U.exec($);if(B){k[P]=B[0],this.#i(i,b,t,v.#r,k),B[0].length===$.length&&b.#t["*"]&&this.#i(i,b.#t["*"],t,v.#r,k);for(let z in b.#t){b.#r=k;let R=B[0].match(/\//g)?.length??0;(s[R]||=[]).push(b);break}continue}}(U===!0||U.test(d))&&(k[P]=d,_?(this.#i(i,b,t,k,v.#r),b.#t["*"]&&this.#i(i,b.#t["*"],t,k,v.#r)):(b.#r=k,p.push(b)))}}}let g=s.shift();o=g?p.concat(g):p}return i[1]&&i.sort((u,d)=>u.score-d.score),[i.map(({handler:u,params:d})=>[u,d])]}};var Yh=class{name="TrieRouter";#e=new yO;add(e,t,n){for(let i of v_(t)||[t])this.#e.insert(e,i,n)}match(e,t){return this.#e.search(e,t)}};var Qh=class extends _O{constructor(e={}){super(e),this.router=e.router??new Kh({routers:[new A_,new Yh]})}};var BX=/^[\w!#$%&'*.^`|~+-]+$/,ZX=/^[!#-:<>-[\]-~]+$/,HX=/^[ !#-:<-[\]-~]*$/,bO=e=>{let t=0,n=e.length;for(;t<n;){let i=e.charCodeAt(t);if(i!==32&&i!==9)break;t++}for(;n>t;){let i=e.charCodeAt(n-1);if(i!==32&&i!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)},ey=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.split(";"),i=Object.create(null);for(let r of n){let o=r.indexOf("=");if(o===-1)continue;let a=bO(r.substring(0,o));if(t&&t!==a||!ZX.test(a)||a in i)continue;let s=bO(r.substring(o+1));if(s.startsWith('"')&&s.endsWith('"')&&(s=s.slice(1,-1)),HX.test(s)&&(i[a]=Ca(s),t))break}return i};var JX=(e,t,n={})=>{if(!BX.test(e))throw new Error("Invalid cookie name");let i=`${e}=${t}`;if(e.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(e.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}for(let r of["domain","path","sameSite","priority"])if(n[r]&&/[;\r\n]/.test(n[r]))throw new Error(`${r} must not contain ";", "\\r", or "\\n"`);if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");i+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(i+=`; Domain=${n.domain}`),n.path&&(i+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");i+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(i+="; HttpOnly"),n.secure&&(i+="; Secure"),n.sameSite&&(i+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(i+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");i+="; Partitioned"}return i},T_=(e,t,n)=>(t=encodeURIComponent(t),JX(e,t,n));var SO=(e,t,n)=>{let i=e.req.raw.headers.get("Cookie");if(typeof t=="string"){if(!i)return;let o=t;return n==="secure"?o="__Secure-"+t:n==="host"&&(o="__Host-"+t),ey(i,o)[o]}return i?ey(i):{}};var GX=(e,t,n)=>{let i;return n?.prefix==="secure"?i=T_("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?i=T_("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):i=T_(e,t,{path:"/",...n}),i},kO=(e,t,n,i)=>{let r=GX(t,n,i);e.header("Set-Cookie",r,{append:!0})};var wO=require("node:crypto"),Qt=require("node:fs"),mc=require("node:path"),KX=/^(?:(?:access|refresh|session|ui|auth)[_-]?)?token$|authorization|cookie|password|secret|credential|api[_-]?key/i,XX=/\x1b\][^\x07]*(?:\x07|\x1b\\)/g,YX=/\x1b\[[0-?]*[ -/]*[@-~]/g;function Na(e,t=0){if(t>6)return"[depth limited]";if(typeof e=="string"){let n=e.replace(XX,"").replace(YX,"");for(let i of[process.env.ZAIP_UI_TOKEN,process.env.ZAIP_SESSION_TOKEN])i&&(n=n.replaceAll(i,"[redacted]"));return n.replace(/(Bearer\s+)[^\s"']+/gi,"$1[redacted]").replace(/((?:token|authorization|cookie|password|secret|api[_-]?key)["']?\s*[:=]\s*["']?)[^\s"',};&]+/gi,"$1[redacted]").replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@").slice(0,16e3)}return e instanceof Error?Na({name:e.name,message:e.message,stack:e.stack,...Object.fromEntries(Object.entries(e))},t+1):Array.isArray(e)?e.slice(0,200).map(n=>Na(n,t+1)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).slice(0,100).map(([n,i])=>[n,KX.test(n)?"[redacted]":Na(i,t+1)])):typeof e=="bigint"?String(e):e}function x_(e,t,n={}){let i=process.env.ZAIP_DASHBOARD_LAUNCH_ID,r=/^[a-zA-Z0-9-]{1,80}$/.test(i??"")?i:(0,wO.randomUUID)(),o=(0,mc.join)(e,".local","dashboard-logs"),a=(0,mc.join)(o,`${t}-${r}-${process.pid}.jsonl`),s=n.maxBytes??2*1024*1024,l=!1,c=!1;return{log:(d,_={})=>{try{if((0,Qt.mkdirSync)(o,{recursive:!0,mode:448}),!l){l=!0;let p=(0,Qt.readdirSync)(o).filter(g=>/^(?:native|launcher|runtime|reconciliation)-[a-zA-Z0-9-]+\.jsonl(?:\.1)?$/.test(g)).map(g=>({name:g,modified:(0,Qt.statSync)((0,mc.join)(o,g)).mtimeMs})).sort((g,m)=>m.modified-g.modified);for(let[g,m]of p.entries())(g>=60||Date.now()-m.modified>14*864e5)&&(0,Qt.unlinkSync)((0,mc.join)(o,m.name))}if((0,Qt.statSync)(a,{throwIfNoEntry:!1})?.size>=s){let p=`${a}.1`;(0,Qt.statSync)(p,{throwIfNoEntry:!1})&&(0,Qt.unlinkSync)(p),(0,Qt.renameSync)(a,p)}return(0,Qt.appendFileSync)(a,`${JSON.stringify({...Na(_),schema_version:1,occurred_at:new Date().toISOString(),component:t,event:d,correlation_id:r,pid:process.pid})}
|
|
351
|
+
`)},xD=e=>{let t=e.socket.encrypted?"https":"http",n=new URL(e.url??"/",`${t}://${e.headers.host??"localhost"}`),i=new Headers;for(let r in e.headers){let o=e.headers[r];o&&i.append(r,Array.isArray(o)?o[0]:o)}return new Request(n,{headers:i})},RD=e=>{let{server:t,fetchCallback:n,wss:i}=e,r=new Map;i.on("connection",(s,l)=>{let c=r.get(l);c&&(c.resolve(s),r.delete(l))});let o=s=>{let l=r.get(s);l&&(r.delete(s),l.reject(new Error("WebSocket handshake aborted")))},a=(s,l)=>new Promise((c,u)=>{r.set(s,{resolve:c,reject:u,connectionSymbol:l})});t.on("upgrade",async(s,l,c)=>{if(s.headers.upgrade?.toLowerCase()!=="websocket")return;let u={incoming:s,outgoing:void 0,wss:i,[qS]:a},d=400,_;try{let f=await n(xD(s),u);f instanceof Response&&(d=f.status,_=f.headers)}catch{t.listenerCount("upgrade")===1&&OS(l,500);return}let p=r.get(s);if(!p||p.connectionSymbol!==u[zS]){o(s),t.listenerCount("upgrade")===1&&OS(l,d,_);return}let g=f=>{VS(f,_)},m=()=>o(s);l.once("close",m),i.on("headers",g);try{i.handleUpgrade(s,l,c,f=>{l.off("close",m),i.emit("connection",f,s)})}finally{i.off("headers",g)}}),t.on("close",()=>{i.close()})},OQ=kS(async(e,t,n)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let i=e.env,r=i[qS];if(!r||!i.incoming)return new Response(null,{status:500});let o=AD();return i[zS]=o,(async()=>{let a;try{a=await r(i.incoming,o)}catch{return}let s=[],l=(d,_)=>{s.push([d,_])};a.on("message",l);let c={binaryType:"arraybuffer",close(d,_){a.close(d,_)},protocol:a.protocol,raw:a,get readyState(){return a.readyState},send(d,_){a.send(d,{compress:_?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),c)}catch(d){(n?.onError??console.error)(d)}let u=(d,_)=>{let p=Array.isArray(d)?d:[d];for(let g of p)try{t?.onMessage?.(new MessageEvent("message",{data:_?g instanceof ArrayBuffer?g:g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength):typeof g=="string"?g:Buffer.from(g).toString("utf-8")}),c)}catch(m){(n?.onError??console.error)(m)}};a.off("message",l);for(let d of s)u(...d);a.on("message",(d,_)=>{u(d,_)}),a.on("close",(d,_)=>{try{t?.onClose?.(new wD("close",{code:d,reason:_.toString()}),c)}catch(p){(n?.onError??console.error)(p)}}),a.on("error",d=>{try{t?.onError?.(new ED("error",{error:d}),c)}catch(_){(n?.onError??console.error)(_)}})})(),new Response}),OD=e=>{let t=e.fetch,n=kD(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),i=(e.createServer||El.createServer)(e.serverOptions||{},n);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw new Error("WebSocket server must be created with { noServer: true } option");RD({server:i,fetchCallback:t,wss:e.websocket.server})}return i},WS=(e,t)=>{let n=OD(e);return n.listen(e?.port??3e3,e.hostname,()=>{let i=n.address();t&&t(i)}),n};var BS=require("node:stream"),ZS=require("node:process"),CD=()=>{let[e,t]=ZS.versions.node.split(".").map(n=>parseInt(n));return e>=23||e===22&&t>=7||e===20&&t>=18},ID=CD(),Um=(e,t=ID)=>{if(t)return BS.Readable.toWeb(e);let n,i=!1,r=()=>{e.off("data",a),e.off("error",s),e.off("end",l),e.off("close",l)},o=c=>{i||(i=!0,r(),c?.())},a=c=>{i||!n||(n.enqueue(c),(n.desiredSize??0)<=0&&e.pause())},s=c=>{o(()=>{n?.error(c)})},l=()=>{o(()=>{n?.close()})};return new ReadableStream({start(c){n=c,e.on("data",a),e.on("error",s),e.on("end",l),e.on("close",l),e.pause()},pull(){i||e.resume()},cancel(){o();let c=()=>{};e.on("error",c),e.once("close",()=>e.off("error",c)),e.destroy()}})};var HS=(e,t=PD)=>{let n=/\.([a-zA-Z0-9]+?)$/,i=e.match(n);if(i)return t[i[1].toLowerCase()]};var ND={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css; charset=utf-8",csv:"text/csv; charset=utf-8",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html; charset=utf-8",html:"text/html; charset=utf-8",ico:"image/x-icon",ics:"text/calendar; charset=utf-8",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript; charset=utf-8",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript; charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml; charset=utf-8",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain; charset=utf-8",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml; charset=utf-8",xml:"application/xml; charset=utf-8",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},PD=ND;var go=require("node:fs"),zm=require("node:path"),$D=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,qm={br:".br",zstd:".zst",gzip:".gz"},LD=Object.keys(qm),Fm=e=>{let t;try{t=(0,go.statSync)(e)}catch{}return t},MD=/^(?:bytes=)?(?!-$)(\d*)-(\d*)$/,DD=e=>{let t=e.match(MD);if(!t)return;let[,n,i]=t;return n===""?{type:"suffix",length:Number(i)}:i===""?{type:"open-ended",start:Number(n)}:{type:"bounded",start:Number(n),end:Number(i)}},jD=(e,t)=>{if(t===0)return;if(e.type==="suffix")return e.length===0?void 0:{start:Math.max(t-e.length,0),end:t-1};let n=e.type==="bounded"?Math.min(e.end,t-1):t-1;if(!(e.start>=t||e.start>n))return{start:e.start,end:n}},UD=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},FD=e=>UD(e,decodeURI),Al=(e={root:""})=>{let t=e.root||"",n=e.path;return t!==""&&!(0,go.existsSync)(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(i,r)=>{if(i.finalized)return r();let o;if(n)o=n;else try{if(o=FD(i.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(o))throw new Error}catch{return await e.onNotFound?.(i.req.path,i),r()}let a=(0,zm.join)(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(o,i):o),s=Fm(a);if(s&&s.isDirectory()){let _=e.index??"index.html";a=(0,zm.join)(a,_),s=Fm(a)}if(!s)return await e.onNotFound?.(a,i),r();let l=HS(a);if(i.header("Content-Type",l||"application/octet-stream"),e.precompressed&&(!l||l==="application/octet-stream"||$D.test(l))){let _=new Set(i.req.header("Accept-Encoding")?.split(",").map(p=>p.trim()));for(let p of LD){if(!_.has(p))continue;let g=Fm(a+qm[p]);if(g){i.header("Content-Encoding",p),i.header("Vary","Accept-Encoding",{append:!0}),s=g,a=a+qm[p];break}}}let c,u=s.size,d=i.req.header("range")||"";if(i.header("Last-Modified",s.mtime.toUTCString()),i.req.method=="HEAD"||i.req.method=="OPTIONS")i.header("Content-Length",u.toString()),i.status(200),c=i.body(null);else if(!d)i.header("Content-Length",u.toString()),c=i.body(Um((0,go.createReadStream)(a)),200);else{i.header("Accept-Ranges","bytes");let _=jD(DD(d)??{type:"open-ended",start:0},u);if(!_)i.header("Content-Range",`bytes */${u}`),c=i.body(null,416);else{let{start:p,end:g}=_,m=g-p+1,f=(0,go.createReadStream)(a,{start:p,end:g});i.header("Content-Length",m.toString()),i.header("Content-Range",`bytes ${p}-${g}/${u}`),c=i.body(Um(f),206)}}return await e.onFound?.(a,i),c}};qe();var zh=(e,t,n)=>(i,r)=>{let o=-1;return a(0);async function a(s){if(s<=o)throw new Error("next() called multiple times");o=s;let l,c=!1,u;if(e[s]?(u=e[s][0][0],i.req.routeIndex=s):u=s===e.length&&r||void 0,u)try{l=await u(i,()=>a(s+1))}catch(d){if(d instanceof Error&&t)i.error=d,l=await t(d,i),c=!0;else throw d}else i.finalized===!1&&n&&(l=await n(i));return l&&(i.finalized===!1||c)&&(i.res=l),i}};var HR=Symbol();var JR=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,i=>i.toLowerCase())}}).formData();var GR=32,PX=1e4,h_=e=>"headers"in e,YR=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=(h_(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return a==="multipart/form-data"||a==="application/x-www-form-urlencoded"?$X(e,{all:n,dot:i}):{}};async function $X(e,t){if(!h_(e)&&e.bodyCache.formData)return KR(await e.bodyCache.formData,t);let n=h_(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),r=JR(i,n.get("Content-Type")||"");h_(e)||(e.bodyCache.formData=r);let o=await r;return o?KR(o,t):{}}function KR(e,t){let n=Object.create(null),i={count:0};return e.forEach((r,o)=>{t.all||o.endsWith("[]")?LX(n,o,r):n[o]=r}),t.dot&&Object.entries(n).forEach(([r,o])=>{r.includes(".")&&(MX(n,r,o,i),delete n[r])}),n}var LX=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n},MX=(e,t,n,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let r=e,o=t.split(".",GR+2);o.length>GR+1&&XR(),o.forEach((a,s)=>{s===o.length-1?r[a]=n:((!r[a]||typeof r[a]!="object"||Array.isArray(r[a])||r[a]instanceof File)&&(i.count++>=PX&&XR(),r[a]=Object.create(null)),r=r[a])})},XR=()=>{throw new Error("Nesting limit exceeded")};var Vh=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},QR=e=>{let{groups:t,path:n}=DX(e),i=Vh(n);return jX(i,t)},DX=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,i)=>{let r=`@${i}`;return t.push([r,n]),r}),{groups:t,path:e}},jX=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[i]=t[n];for(let r=e.length-1;r>=0;r--)if(e[r].includes(i)){e[r]=e[r].replace(i,t[n][1]);break}}return e},y_={},eO=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let i=`${e}#${t}`;return y_[i]||(n[2]?y_[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:y_[i]=[e,n[1],!0]),y_[i]}return null},tO=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},UX=e=>tO(e,decodeURI),Wh=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),i=n;for(;i<t.length;i++){let r=t.charCodeAt(i);if(r===37){let o=t.indexOf("?",i),a=t.indexOf("#",i),s=o===-1?a===-1?void 0:a:a===-1?o:Math.min(o,a),l=t.slice(n,s);return UX(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(r===63||r===35)break}return t.slice(n,i)};var nO=e=>{let t=Wh(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Gi=(e,t,...n)=>(n.length&&(t=Gi(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),v_=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],i="";return t.forEach(r=>{if(r!==""&&!/\:/.test(r))i+="/"+r;else if(/\:/.test(r))if(r.charCodeAt(r.length-1)===63){n.length===0&&i===""?n.push("/"):n.push(i);let o=r.slice(0,-1);i+="/"+o,n.push(i)}else i+="/"+r}),n.filter((r,o,a)=>a.indexOf(r)===o)},Ca=e=>e.indexOf("%")!==-1?tO(e,FX):e,qh=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Ca(e)),rO=(e,t,n)=>{let i=e.indexOf("#",8);i!==-1&&(e=e.slice(0,i));let r;if(!n&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let s=e.indexOf("?",8);if(s===-1)return;for(e.startsWith(t,s+1)||(s=e.indexOf(`&${t}`,s+1));s!==-1;){let l=e.charCodeAt(s+t.length+1);if(l===61){let c=s+t.length+2,u=e.indexOf("&",c);return qh(e.slice(c,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";s=e.indexOf(`&${t}`,s+1)}if(r=/[%+]/.test(e),!r)return}let o=Object.create(null);r??=/[%+]/.test(e);let a=e.indexOf("?",8);for(;a!==-1;){let s=e.indexOf("&",a+1),l=e.indexOf("=",a);l>s&&s!==-1&&(l=-1);let c=e.slice(a+1,l===-1?s===-1?void 0:s:l);if(r&&(c=qh(c)),a=s,c==="")continue;let u;l===-1?u="":(u=e.slice(l+1,s===-1?void 0:s),r&&(u=qh(u))),n?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(u)):o[c]??=u}return t?o[t]:o},iO=rO,oO=(e,t)=>rO(e,t,!0),FX=decodeURIComponent;var aO=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#o()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#r(t);return n&&Ca(n)}#o(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let i=this.#r(this.#t[0][this.routeIndex][1][n]);i!==void 0&&(e[n]=Ca(i))}return e}#r(e){return this.#t[1]?this.#t[1][e]:e}query(e){return iO(this.url,e)}queries(e){return oO(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((n,i)=>{t[i]=n}),t}async parseBody(e){return YR(this,e)}#i=e=>{let{bodyCache:t,raw:n}=this,i=t[e];if(i)return i;for(let r in t)return t[r].then(o=>(r==="json"&&(o=JSON.stringify(o)),new Response(o)[e]()));return t[e]=n[e]()};json(){return this.#i("text").then(e=>JSON.parse(e))}text(){return this.#i("text")}arrayBuffer(){return this.#i("arrayBuffer")}bytes(){return this.#i("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#i("blob")}formData(){return this.#i("formData")}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[HR](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};var b_={Stringify:1,BeforeStream:2,Stream:3},zX=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var _c=async(e,t,n,i,r)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);r?r[0]+=e:r=[e];let a=Promise.all(o.map(s=>s({phase:t,buffer:r,context:i}))).then(s=>Promise.all(s.filter(Boolean).map(l=>_c(l,t,!1,i,r))).then(()=>r[0]));return n?zX(await a,o):a};var sO="text/plain; charset=UTF-8",Bh=(e,t)=>({"Content-Type":e,...t}),pc=(e,t)=>new Response(e,t),Zh=class{#e;#t;env={};#n;finalized=!1;error;#o;#r;#i;#u;#c;#l;#s;#d;#_;constructor(e,t){this.#e=e,t&&(this.#r=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#_=t.path,this.#d=t.matchResult)}get req(){return this.#t??=new aO(this.#e,this.#_,this.#d),this.#t}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#i||=pc(null,{headers:this.#s??=new Headers})}set res(e){if(this.#i&&e){e=pc(e.body,e);for(let[t,n]of this.#i.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let i=this.#i.headers.getSetCookie();e.headers.delete("set-cookie");for(let r of i)e.headers.append("set-cookie",r)}else e.headers.set(t,n)}this.#i=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,n)=>{this.finalized&&(this.#i=pc(this.#i.body,this.#i));let i=this.#i?this.#i.headers:this.#s??=new Headers;t===void 0?i.delete(e):n?.append?i.append(e,t):i.set(e,t)};status=e=>{this.#o=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#a(e,t,n){let i=this.#i?new Headers(this.#i.headers):this.#s;if(typeof t=="object"&&t.headers){i??=new Headers;for(let[o,a]of new Headers(t.headers))o==="set-cookie"?i.append(o,a):i.set(o,a)}if(n){if(!i){let o=0;for(let a in n)if(++o>1||typeof n[a]!="string"){i=new Headers;break}}if(i)for(let o in n){let a=n[o];if(typeof a=="string")i.set(o,a);else{i.delete(o);for(let s of a)i.append(o,s)}}}let r=typeof t=="number"?t:t?.status??this.#o;return pc(e,{status:r,headers:i??n})}newResponse=(...e)=>this.#a(...e);body=(e,t,n)=>this.#a(e,t,n);text=(e,t,n)=>!this.#s&&!this.#o&&!t&&!n&&!this.finalized?new Response(e):this.#a(e,t,Bh(sO,n));json=(e,t,n)=>this.#a(JSON.stringify(e),t,Bh("application/json",n));html=(e,t,n)=>{let i=r=>this.#a(r,t,Bh("text/html; charset=UTF-8",n));return typeof e=="object"?_c(e,b_.Stringify,!1,{}).then(i):i(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>pc(),this.#l(this))};var Vt="ALL",cO="all",lO=["get","post","put","delete","options","patch","query"],S_="Can not add a route since the matcher is already built.",k_=class extends Error{};var uO="__COMPOSED_HANDLER";var qX=e=>e.text("404 Not Found",404),dO=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},_O=class pO{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...lO,cO].forEach(o=>{this[o]=(a,...s)=>{let l=o.toUpperCase();return typeof a=="string"?this.#e=a:this.#o(l,this.#e,a),s.forEach(c=>{this.#o(l,this.#e,c)}),this}}),this.on=(o,a,...s)=>{for(let l of[a].flat()){this.#e=l;for(let c of[o].flat()){let u=c.toUpperCase();for(let d of s)this.#o(u,this.#e,d)}}return this},this.use=(o,...a)=>(typeof o=="string"?this.#e=o:(this.#e="*",a.unshift(o)),a.forEach(s=>{this.#o(Vt,this.#e,s)}),this);let{strict:i,...r}=t;Object.assign(this,r),this.getPath=i??!0?t.getPath??Wh:nO}#t(){let t=new pO({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=qX;errorHandler=dO;route(t,n){let i=this.basePath(t);return n.routes.map(r=>{let o;n.errorHandler===dO?o=r.handler:(o=async(a,s)=>(await zh([],n.errorHandler)(a,()=>r.handler(a,s))).res,o[uO]=r.handler),i.#o(r.method,r.path,o,r.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=Gi(this._basePath,t),n}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#n=t,this);mount(t,n,i){let r,o;i&&(typeof i=="function"?o=i:(o=i.optionHandler,i.replaceRequest===!1?r=l=>l:r=i.replaceRequest));let a=o?l=>{let c=o(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx}catch{}return[l.env,c]};r||=(()=>{let l=Gi(this._basePath,t),c=l==="/"?0:l.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(c)||"/",new Request(d,u)}})();let s=async(l,c)=>{let u=await n(r(l.req.raw),...a(l));if(u)return u;await c()};return this.#o(Vt,Gi(t,"*"),s),this}#o(t,n,i,r){n=Gi(this._basePath,n);let o={basePath:r!==void 0?Gi(this._basePath,r):this._basePath,path:n,method:t,handler:i};this.router.add(t,n,[i,o]),this.routes.push(o)}#r(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#i(t,n,i,r){if(r==="HEAD")return(async()=>new Response(null,await this.#i(t,n,i,"GET")))();let o=this.getPath(t,{env:i}),a=this.router.match(r,o),s=new Zh(t,{path:o,matchResult:a,env:i,executionCtx:n,notFoundHandler:this.#n});if(a[0].length===1){let c;try{c=a[0][0][0][0](s,async()=>{s.res=await this.#n(s)})}catch(u){return this.#r(u,s)}return c instanceof Promise?c.then(u=>u||(s.finalized?s.res:this.#n(s))).catch(u=>this.#r(u,s)):c??this.#n(s)}let l=zh(a[0],this.errorHandler,this.#n);return(async()=>{try{let c=await l(s);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#r(c,s)}})()}fetch=(t,...n)=>this.#i(t,n[1],n[0],t.method);request=(t,n,i,r)=>t instanceof Request?this.fetch(n?new Request(t,n):t,i,r):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Gi("/",t)}`,n),i,r));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#i(t.request,t,void 0,t.request.method))})}};var Lt=()=>Object.create(null);var w_=[];function Hh(e,t){let n=this.buildAllMatchers(),i=((r,o)=>{let a=n[r]||n[Vt],s=a[2][o];if(s)return s;let l=o.match(a[0]);if(!l)return[[],w_];let c=l.indexOf("",1);return[a[1][c],l]});return this.match=i,i(e,t)}var Ia="[^/]+",Xi=".*",ki="(?:|/.*)",Ki=Symbol(),mO=new Set(".\\+*[^]$()");function VX(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===Xi||e===ki?t===ki?-1:1:t===Xi||t===ki?-1:e===Ia?1:t===Ia?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var fO=class Jh{#e;#t;#n=Lt();insert(t,n,i,r,o){let a=this;for(let s=0,l=t.length;s<l;s++){let c=t[s],u=c.length===1?c==="*"?s===l-1?["","",Xi]:["","",Ia]:null:c==="/*"?["","",ki]:c.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let _=u[1],p=u[2]||Ia;if(_&&u[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))||p.length===1&&mO.has(p)))throw Ki;if(d=a.#n[p],!d){if(p!==Xi&&p!==ki){for(let g in a.#n)if((p.length>1||g.length>1)&&g!==Xi&&g!==ki)throw Ki}d=a.#n[p]=new Jh}_!==""&&(d.#t??=r.varIndex++,i.push([_,d.#t]))}else if(d=a.#n[c],!d){for(let _ in a.#n)if(_.length>1&&_!==Xi&&_!==ki)throw Ki;d=a.#n[c]=new Jh}a=d}if(a.#e!==void 0)throw Ki;a.#e=o?-1:n}buildRegExpStr(){let n=Object.keys(this.#n).sort(VX).map(i=>{let r=this.#n[i],o=r.buildRegExpStr();return o===""?"":(typeof r.#t=="number"?`(${i})@${r.#t}`:mO.has(i)?`\\${i}`:i)+o}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&n.unshift(`#${this.#e}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var Gh=class{#e={varIndex:0};#t=new fO;#n=0;paths=Lt();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let n=[],i=[],r=e;for(let a=0;;){let s=!1;if(r=r.replace(/\{[^}]+\}/g,l=>{let c=`@\\${a}`;return i[a]=[c,l],a++,s=!0,c}),!s)break}let o=r.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=i.length-1;a>=0;a--){let[s]=i[a];for(let l=o.length-1;l>=0;l--)if(o[l].indexOf(s)!==-1){o[l]=o[l].replace(s,i[a][1]);break}}this.#t.insert(o,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],i=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(r,o,a)=>o!==void 0?(n[++t]=Number(o),"$()"):(a!==void 0&&(i[Number(a)]=++t),"")),[new RegExp(`^${e}`),n,i]}};var gO=Lt();function hO(e){return gO[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,n)=>n?`\\${n}`:t==="/*"?ki:t==="*"?Xi:`/:${Ia}`)}$`)}function E_(e,t){for(let n of Object.keys(e).sort((i,r)=>r.length-i.length))if(hO(n).test(t))return[...e[n]]}var A_=class{name="RegExpRouter";#e;#t;#n;constructor(){this.#e={[Vt]:Lt()},this.#t={[Vt]:Lt()},this.#n={[Vt]:new Gh}}#o(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===Ki?new k_(t):n}}add(e,t,n){let i=this.#e,r=this.#t;if(!i)throw new Error(S_);if(!i[e]){this.#n[e]=new Gh;for(let s of[i,r]){s[e]=Lt();for(let l in s[Vt])s[e][l]=[...s[Vt][l]],this.#o(e,l)}}t==="/*"&&(t="*");let o=e===Vt?Object.keys(i):[e];if(/\*$/.test(t)){let s=hO(t);for(let l of o)i[l][t]||(this.#o(l,t),i[l][t]=E_(i[l],t)||E_(i[Vt],t)||[]);for(let l of[i,r])for(let c of o)for(let u in l[c])s.test(u)&&l[c][u].push([n,t]);return}let a=v_(t)||[t];for(let s of a)for(let l of o)r[l][s]||(this.#o(l,s),r[l][s]=E_(i[l],s)||E_(i[Vt],s)||[]),r[l][s].push([n,s])}match=Hh;buildAllMatchers(){let e=Lt();for(let t of Object.keys(this.#t))e[t]=this.#r(t);return this.#e=this.#t=this.#n=void 0,gO=Lt(),e}#r(e){let t=this.#e[e],n=this.#t[e],i=this.#n[e],r=Lt(),o=[],[a,s,l]=i.buildRegExp();for(let c of[t,n])for(let u in c){let d=c[u],_=i.paths[u];if(!_){r[u]=[d.map(([p])=>[p,Lt()]),w_];continue}o[_[0]]=d.map(([p,g])=>[p,i.paths[g][1].reduceRight((m,[f],v)=>(m[f]=l[_[1][v][1]],m),Lt())])}return[a,s.map(c=>o[c]),r]}};var Kh=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw new Error(S_);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw new Error("Fatal error");let n=this.#e,i=this.#t,r=n.length,o=0,a;for(;o<r;o++){let s=n[o];try{for(let l=0,c=i.length;l<c;l++)s.add(...i[l]);a=s.match(e,t)}catch(l){if(l instanceof k_)continue;throw l}this.match=s.match.bind(s),this.#e=[s],this.#t=void 0;break}if(o===r)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var Xh=Lt(),WX=0,yO=class vO{#e=[];#t=Lt();#n=[];#o;#r=Xh;insert(t,n,i){let r=this,o=QR(n),a=new Set,s=0;for(let l of o){let c=o[++s],u=eO(l,c)||(c===void 0&&l&&l.indexOf("*")===l.length-1?l:null),d=Array.isArray(u),_=d?u[0]:u||l,p=r.#t[_]||=new vO;u&&!p.#o&&(p.#o=u,r.#n.push(p)),r=p,d&&a.add(u[1])}r.#e.push({[t]:{handler:i,possibleKeys:[...a],score:++WX}})}#i(t,n,i,r,o){for(let a=0,s=n.#e.length;a<s;a++){let l=n.#e[a],c=l[i]||l[Vt];if(c){c.params=Lt(),t.push(c);for(let u=0,d=c.possibleKeys.length;u<d;u++){let _=c.possibleKeys[u];c.params[_]=o?.[_]&&!u?o[_]:r[_]??o?.[_]}}}}search(t,n){let i=[];this.#r=Xh;let o=[this],a=Vh(n),s=[],l=a.length,c=null;for(let u=0;u<l;u++){let d=a[u],_=u===l-1,p=[];for(let m=0,f=o.length;m<f;m++){let v=o[m],S=v.#t[d];S&&(S.#r=v.#r,_?(S.#t["*"]&&this.#i(i,S.#t["*"],t,v.#r),this.#i(i,S,t,v.#r)):p.push(S));for(let b of v.#n){let h=b.#o,k=v.#r===Xh?{}:{...v.#r};if(typeof h=="string"){(h==="*"||d.startsWith(h.slice(0,-1)))&&(this.#i(i,b,t,v.#r),h==="*"&&(b.#r=k,p.push(b)));continue}let[,P,U]=h;if(!(!d&&U===!0)){if(U!==!0){if(!c){c=[];let z=n[0]==="/"?1:0;for(let R=0;R<l;R++)c[R]=z,z+=a[R].length+1}let $=n.slice(c[u]),B=U.exec($);if(B){k[P]=B[0],this.#i(i,b,t,v.#r,k),B[0].length===$.length&&b.#t["*"]&&this.#i(i,b.#t["*"],t,v.#r,k);for(let z in b.#t){b.#r=k;let R=B[0].match(/\//g)?.length??0;(s[R]||=[]).push(b);break}continue}}(U===!0||U.test(d))&&(k[P]=d,_?(this.#i(i,b,t,k,v.#r),b.#t["*"]&&this.#i(i,b.#t["*"],t,k,v.#r)):(b.#r=k,p.push(b)))}}}let g=s.shift();o=g?p.concat(g):p}return i[1]&&i.sort((u,d)=>u.score-d.score),[i.map(({handler:u,params:d})=>[u,d])]}};var Yh=class{name="TrieRouter";#e=new yO;add(e,t,n){for(let i of v_(t)||[t])this.#e.insert(e,i,n)}match(e,t){return this.#e.search(e,t)}};var Qh=class extends _O{constructor(e={}){super(e),this.router=e.router??new Kh({routers:[new A_,new Yh]})}};var BX=/^[\w!#$%&'*.^`|~+-]+$/,ZX=/^[!#-:<>-[\]-~]+$/,HX=/^[ !#-:<-[\]-~]*$/,bO=e=>{let t=0,n=e.length;for(;t<n;){let i=e.charCodeAt(t);if(i!==32&&i!==9)break;t++}for(;n>t;){let i=e.charCodeAt(n-1);if(i!==32&&i!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)},ey=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.split(";"),i=Object.create(null);for(let r of n){let o=r.indexOf("=");if(o===-1)continue;let a=bO(r.substring(0,o));if(t&&t!==a||!ZX.test(a)||a in i)continue;let s=bO(r.substring(o+1));if(s.startsWith('"')&&s.endsWith('"')&&(s=s.slice(1,-1)),HX.test(s)&&(i[a]=Ca(s),t))break}return i};var JX=(e,t,n={})=>{if(!BX.test(e))throw new Error("Invalid cookie name");let i=`${e}=${t}`;if(e.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(e.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}for(let r of["domain","path","sameSite","priority"])if(n[r]&&/[;\r\n]/.test(n[r]))throw new Error(`${r} must not contain ";", "\\r", or "\\n"`);if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");i+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(i+=`; Domain=${n.domain}`),n.path&&(i+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");i+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(i+="; HttpOnly"),n.secure&&(i+="; Secure"),n.sameSite&&(i+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(i+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");i+="; Partitioned"}return i},T_=(e,t,n)=>(t=encodeURIComponent(t),JX(e,t,n));var SO=(e,t,n)=>{let i=e.req.raw.headers.get("Cookie");if(typeof t=="string"){if(!i)return;let o=t;return n==="secure"?o="__Secure-"+t:n==="host"&&(o="__Host-"+t),ey(i,o)[o]}return i?ey(i):{}};var GX=(e,t,n)=>{let i;return n?.prefix==="secure"?i=T_("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?i=T_("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):i=T_(e,t,{path:"/",...n}),i},kO=(e,t,n,i)=>{let r=GX(t,n,i);e.header("Set-Cookie",r,{append:!0})};var wO=require("node:crypto"),Qt=require("node:fs"),mc=require("node:path"),KX=/^(?:(?:access|refresh|session|ui|auth)[_-]?)?token$|authorization|cookie|password|secret|credential|api[_-]?key/i,XX=/\x1b\][^\x07]*(?:\x07|\x1b\\)/g,YX=/\x1b\[[0-?]*[ -/]*[@-~]/g;function Na(e,t=0){if(t>6)return"[depth limited]";if(typeof e=="string"){let n=e.replace(XX,"").replace(YX,"");for(let i of[process.env.ZAIP_UI_TOKEN,process.env.ZAIP_SESSION_TOKEN])i&&(n=n.replaceAll(i,"[redacted]"));return n.replace(/(Bearer\s+)[^\s"']+/gi,"$1[redacted]").replace(/((?:token|authorization|cookie|password|secret|api[_-]?key)["']?\s*[:=]\s*["']?)[^\s"',};&]+/gi,"$1[redacted]").replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@").slice(0,16e3)}return e instanceof Error?Na({name:e.name,message:e.message,stack:e.stack,...Object.fromEntries(Object.entries(e))},t+1):Array.isArray(e)?e.slice(0,200).map(n=>Na(n,t+1)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).slice(0,100).map(([n,i])=>[n,KX.test(n)?"[redacted]":Na(i,t+1)])):typeof e=="bigint"?String(e):e}function x_(e,t,n={}){let i=process.env.ZAIP_DASHBOARD_LAUNCH_ID,r=/^[a-zA-Z0-9-]{1,80}$/.test(i??"")?i:(0,wO.randomUUID)(),o=(0,mc.join)(e,".local","dashboard-logs"),a=(0,mc.join)(o,`${t}-${r}-${process.pid}.jsonl`),s=n.maxBytes??2*1024*1024,l=!1,c=!1;return{log:(d,_={})=>{try{if((0,Qt.mkdirSync)(o,{recursive:!0,mode:448}),!l){l=!0;let p=(0,Qt.readdirSync)(o).filter(g=>/^(?:native|launcher|runtime|reconciliation)-[a-zA-Z0-9-]+\.jsonl(?:\.1)?$/.test(g)).map(g=>({name:g,modified:(0,Qt.statSync)((0,mc.join)(o,g)).mtimeMs})).sort((g,m)=>m.modified-g.modified);for(let[g,m]of p.entries())(g>=60||Date.now()-m.modified>14*864e5)&&(0,Qt.unlinkSync)((0,mc.join)(o,m.name))}if((0,Qt.statSync)(a,{throwIfNoEntry:!1})?.size>=s){let p=`${a}.1`;(0,Qt.statSync)(p,{throwIfNoEntry:!1})&&(0,Qt.unlinkSync)(p),(0,Qt.renameSync)(a,p)}return(0,Qt.appendFileSync)(a,`${JSON.stringify({...Na(_),schema_version:1,occurred_at:new Date().toISOString(),component:t,event:d,correlation_id:r,pid:process.pid})}
|
|
352
352
|
`,{encoding:"utf8",mode:384}),!0}catch{return c||process.stderr.write(`Dashboard diagnostic log unavailable in .local/dashboard-logs
|
|
353
353
|
`),c=!0,!1}},path:a,correlationId:r}}function EO(e){let t=e instanceof Error?e:null,n=t,i=n?.code,r=n?.signal,o=Number.isSafeInteger(i)?i:null,a=typeof i=="string"&&["ENOENT","EACCES","EPERM","ETIMEDOUT","ERR_CHILD_PROCESS_STDIO_MAXBUFFER"].includes(i)?i:null,s=typeof r=="string"&&/^SIG[A-Z0-9]{1,12}$/.test(r)?r:null;return{code:"active_telemetry_capture_failed",occurred_at:new Date().toISOString(),cause:t===null?"unknown_error":"Error",failure_kind:a==="ETIMEDOUT"?"timeout":a==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"output_limit":n?.killed===!0||s!==null?"process_terminated":o!==null?"process_exit":a!==null?"spawn_failure":"capture_error",process_code:a,exit_code:o,signal:s}}var $O=require("node:child_process"),ty=require("node:path"),LO=require("node:util");qe();var wi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),AO=e=>typeof e=="string"&&Number.isFinite(Date.parse(e));async function fc(e){let t=".agents/records/lifecycle",[n,i]=await Promise.all([e.exists(`${t}/manifest.json`),e.exists(`${t}/summary.json`)]);if(!n&&!i)return"missing";if(!n||!i)return"invalid";try{let[r,o]=await Promise.all([e.readText(`${t}/manifest.json`).then(a=>JSON.parse(a)),e.readText(`${t}/summary.json`).then(a=>JSON.parse(a))]);return!wi(r)||r.schema_version!==1||!AO(r.updated_at)||!wi(r.offsets)||!Object.values(r.offsets).every(a=>Number.isSafeInteger(a)&&Number(a)>=0)||!wi(o)||o.schema_version!==1||!AO(o.updated_at)||!wi(o.counts)||!Number.isSafeInteger(o.counts.total)||Number(o.counts.total)<0||!wi(o.counts.by_kind)||!wi(o.counts.by_status)||!wi(o.freshness)||!wi(o.usage)||!wi(o.periods)?"invalid":"initialized"}catch{return"invalid"}}var OO=require("node:child_process"),CO=require("node:crypto"),Oo=require("node:fs/promises"),Ei=require("node:path"),IO=require("node:util");var C_=require("node:crypto"),en=require("node:fs/promises"),gc=require("node:path"),R_=2e5,TO=128*1024*1024;function xO(e){return[e.dev,e.ino,e.birthtimeNs,e.mtimeNs,e.ctimeNs,e.size].join(":")}function QX(e,t){if(t.endsWith(".jsonl")){let r=[...e.matchAll(/"occurred_at"\s*:\s*"([^"]+)"/gu)];return[r.reduce((o,a)=>(a[1]??"")>o?a[1]:o,""),r.length,e.length]}let n=/^updated_at:\s*([^\r\n]+)/mu.exec(e)?.[1]?.trim()??"",i=/^created_at:\s*([^\r\n]+)/mu.exec(e)?.[1]?.trim()??"";return[n||i,Number(/^revision:\s*(\d+)/mu.exec(e)?.[1]??0),e.length]}function eY(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.metadata=="string"&&/^\d+(?::\d+){5}$/u.test(t.metadata)&&typeof t.contentHash=="string"&&/^[a-f0-9]{64}$/u.test(t.contentHash)&&typeof t.settled=="boolean"&&Array.isArray(t.revision)&&t.revision.length===3&&typeof t.revision[0]=="string"&&t.revision[0].length<=256&&Number.isSafeInteger(t.revision[1])&&t.revision[1]>=0&&Number.isSafeInteger(t.revision[2])&&t.revision[2]>=0}var O_=class e{constructor(t,n){this.path=t;this.verify=n}path;verify;entries=new Map;seen=new Set;dirty=!1;reads=0;reused=0;static async open(t,n=!1){let i=new e((0,gc.resolve)(t,".local/cache/dashboard-canonical-revisions-v1.json"),n);if(n)return i;try{if((await(0,en.stat)(i.path)).size>TO)return i;let r=JSON.parse(await(0,en.readFile)(i.path,"utf8"));if(r.version!==1||!Array.isArray(r.entries)||r.entries.length>R_)return i;for(let o of r.entries)!Array.isArray(o)||o.length!==2||typeof o[0]!="string"||o[0].length>4096||!eY(o[1])||i.entries.set(o[0],o[1])}catch{}return i}async read(t,n){let i=(0,gc.resolve)(t);this.seen.size<R_&&this.seen.add(i);try{for(let r=0;r<3;r+=1){let o=await(0,en.stat)(i,{bigint:!0}),a=xO(o),s=Date.now()-Number(o.ctimeMs)>2e3,l=this.entries.get(i);if(!this.verify&&s&&l?.settled&&l.metadata===a)return this.reused+=1,{entry:l,metadata:o,reused:!0};let c=await(0,en.readFile)(i);if(this.reads+=1,xO(await(0,en.stat)(i,{bigint:!0}))!==a)continue;let u={metadata:a,settled:s,revision:QX(c.toString("utf8"),n),contentHash:(0,C_.createHash)("sha256").update(c).digest("hex")};return!this.verify&&this.seen.has(i)&&(this.entries.has(i)||this.entries.size<R_)&&(this.entries.set(i,u),this.dirty=!0),{entry:u,metadata:o,reused:!1}}throw new Error(`Canonical source changed repeatedly during revision selection: ${n}`)}catch(r){if(r.code==="ENOENT")return this.entries.delete(i),this.dirty=!0,null;throw r}}async persist(){if(this.verify)return;for(let r of this.entries.keys())this.seen.has(r)||(this.entries.delete(r),this.dirty=!0);if(!this.dirty)return;let t=[...this.entries].slice(-R_),n=JSON.stringify({version:1,entries:t});if(Buffer.byteLength(n)>TO)return;let i=`${this.path}.${(0,C_.randomUUID)()}.tmp`;try{await(0,en.mkdir)((0,gc.dirname)(this.path),{recursive:!0}),await(0,en.writeFile)(i,n,{flag:"wx"}),await(0,en.rename)(i,this.path)}catch{}finally{await(0,en.rm)(i,{force:!0}).catch(()=>{})}}};var RO=(0,IO.promisify)(OO.execFile),tY=new Set([".json",".jsonl",".md",".yaml",".yml",".txt"]);function nY(e){let t="\\.agents\\/(?:data|records)";return[".agents/config/project.yaml",".agents/config/framework.lock.yaml",".agents/config/agents/catalog.yaml",".agents/config/clients.yaml"].includes(e)||e.startsWith(".agents/config/pricing/")||new RegExp(`^${t}/runs/`).test(e)&&e.endsWith(".jsonl")||new RegExp(`^${t}/(tasks|specs|prds)/.*\\.md$`).test(e)||new RegExp(`^${t}/executions/.*/execution\\.md$`).test(e)||new RegExp(`^${t}/executions/.*/decisions/.*\\.md$`).test(e)||new RegExp(`^${t}/lifecycle/historical-developer-attribution/`).test(e)&&e.endsWith(".json")?!0:new RegExp(`^${t}/changes/.*/(change\\.md|decisions/.*\\.md|artifacts/(evidence|tests|validations)/.*\\.md)$`).test(e)}async function hc(e){let t=(0,Ei.resolve)(e),n=await RO("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",windowsHide:!0,timeout:5e3}).catch(()=>({stdout:""}));if((0,Ei.resolve)(n.stdout.trim()).toLowerCase()!==t.toLowerCase())return[t];let r=(await RO("git",["worktree","list","--porcelain"],{cwd:t,encoding:"utf8",windowsHide:!0,timeout:15e3}).catch(()=>({stdout:""}))).stdout.split(/\r?\n/u).filter(a=>a.startsWith("worktree ")).map(a=>(0,Ei.resolve)(a.slice(9).trim())),o=r.filter(rY);return[...new Set([t,...r.slice(0,1),...o])]}function rY(e){return/[\\/]\.codex[\\/]worktrees(?:[\\/][^\\/]+){1,2}$/iu.test(e)}async function iY(e,t){let n=new Map;for(let[o,a]of e.entries()){let s=o===0?[".agents/config",...["tasks","specs","prds","runs","executions","changes","lifecycle/historical-developer-attribution"].flatMap(c=>[`.agents/data/${c}`,`.agents/records/${c}`])]:["tasks","specs","prds","runs","executions","changes","lifecycle/historical-developer-attribution"].map(c=>`.agents/records/${c}`),l=(await Promise.all(s.map(c=>NO((0,Ei.resolve)(a,c))))).flat();for(let c of l){let u=(0,Ei.relative)(a,c).replaceAll("\\","/");if(!tY.has(c.slice(c.lastIndexOf(".")).toLowerCase())||!nY(u))continue;let d=n.get(u)??[];d.push(c),n.set(u,d)}}let i=[],r=[...n.entries()];for(let o=0;o<r.length;o+=32)i.push(...(await Promise.all(r.slice(o,o+32).map(async([a,s])=>{let l=s[0];if(l===void 0)throw new Error(`No canonical source for ${a}`);if(s.length===1)return{source:a,path:l};let c=await Promise.all(s.map(_=>t.read(_,a))),u=c.findIndex(_=>_!==null);if(u<0)return null;for(let _=1;_<s.length;_+=1){let p=c[_]?.entry.revision,g=c[u]?.entry.revision;if(p){if(!g)throw new Error(`Incomplete canonical revisions for ${a}`);(p[0]>g[0]||p[0]===g[0]&&(p[1]>g[1]||p[1]===g[1]&&p[2]>g[2]))&&(u=_)}}let d=s[u];if(d===void 0)throw new Error(`No selected canonical source for ${a}`);return{source:a,path:d}}))).filter(a=>a!==null));return i.sort((o,a)=>o.source.localeCompare(a.source))}async function I_(e,t={}){let n=await O_.open(e,t.verifyContent),i=await iY(t.sourceRoots??await hc(e),n),r=[],o=0,a=0;for(let s=0;s<i.length;s+=32)r.push(...(await Promise.all(i.slice(s,s+32).map(async({path:l,source:c})=>{try{for(let u=0;u<3;u+=1){let d=await(0,Oo.stat)(l),_=Date.now()-d.ctimeMs>2e3,p={path:l,source:c,mtimeMs:d.mtimeMs,ctimeMs:d.ctimeMs,size:d.size,fileIdentity:`settled-v2:${d.dev}:${d.ino}:${d.birthtimeMs}${_?"":":recent"}`},g=t.previous?.get(c);if(!t.verifyContent&&_&&g!==void 0&&g.mtimeMs===p.mtimeMs&&g.ctimeMs===p.ctimeMs&&g.size===p.size&&g.fileIdentity===p.fileIdentity)return a+=1,{...p,contentHash:g.contentHash};let m=(0,CO.createHash)("sha256").update(await(0,Oo.readFile)(l)).digest("hex"),f=await(0,Oo.stat)(l);if(!(d.mtimeMs!==f.mtimeMs||d.ctimeMs!==f.ctimeMs||d.size!==f.size||d.ino!==f.ino||d.dev!==f.dev||d.birthtimeMs!==f.birthtimeMs))return o+=1,{...p,contentHash:m}}throw new Error(`Canonical source changed repeatedly during refresh: ${c}`)}catch(u){if(u.code==="ENOENT")return null;throw u}}))).filter(l=>l!==null));return await n.persist(),{fingerprint:r.map(s=>`${s.source}:${s.mtimeMs}:${s.size}:${s.contentHash}`).join("|"),candidates:r,hashedFiles:o,reusedFiles:a,duplicateReads:n.reads,duplicateReused:n.reused}}async function NO(e){let t=await(0,Oo.readdir)(e,{withFileTypes:!0}).catch(n=>{if(n.code==="ENOENT")return[];throw n});return(await Promise.all(t.map(async n=>{let i=(0,Ei.join)(e,n.name);return n.isDirectory()?NO(i):n.isFile()?[i]:[]}))).flat()}var oY=(0,LO.promisify)($O.execFile),PO=12e4,ny=class extends Error{code="ETIMEDOUT";deadline_observed=!0;constructor(){super("Recent Codex capture exceeded its observed process deadline")}};async function aY(e,t=e,n=oY,i=AbortSignal.timeout(PO)){let r=await fc(new ei(e));if(r!=="initialized")return{captured_runs:0,captured_segments:0,manifest_state:r,skipped_reason:r==="missing"?"manifest_uninitialized":"manifest_invalid",last_capture_at:new Date().toISOString()};let o=(0,ty.resolve)(t,".agents","runtime","bin","zaip.mjs");try{let a=await n(process.execPath,[o,"--workspace",(0,ty.resolve)(e),"run","usage","--recent","--limit","32","--disable-codex-raw","--json"],{cwd:e,encoding:"utf8",windowsHide:!0,signal:i,timeout:PO+5e3,maxBuffer:1048576}),s=sY(a.stdout),l=cY(s),c=l.captured,u=c.filter(d=>d.captured).length;return{captured_runs:u,catch_up_complete:l.complete,pending_runs:l.pending,captured_segments:u===0?0:null,manifest_state:"initialized",skipped_reason:l.complete?c.length===0?"no_recent_runs":u===0?"no_new_segments":null:"catch_up_pending",last_capture_at:new Date().toISOString()}}catch(a){if(i.aborted&&a instanceof Error&&(a.name==="AbortError"||"code"in a&&a.code==="ABORT_ERR"))throw new ny;if(lY(a))return{captured_runs:0,captured_segments:0,manifest_state:"missing",skipped_reason:"manifest_uninitialized",last_capture_at:new Date().toISOString()};throw a}}async function MO(e,t=e){let n=await hc(e),i=await Promise.all(n.map(a=>aY(a,t))),r=i[0];if(r===void 0)throw new Error("No dashboard workspace was discovered");let o=i.reduce((a,s)=>a+s.captured_runs,0);return{captured_runs:o,catch_up_complete:i.every(a=>a.catch_up_complete!==!1),pending_runs:i.reduce((a,s)=>a+(s.pending_runs??0),0),captured_segments:o===0?0:null,manifest_state:r.manifest_state,skipped_reason:i.some(a=>a.catch_up_complete===!1)?"catch_up_pending":o>0?null:i.some(a=>a.skipped_reason==="no_new_segments")?"no_new_segments":r.skipped_reason,last_capture_at:new Date().toISOString()}}function sY(e){if(!e.trim())throw new Error("Active telemetry capture returned no JSON result");try{return JSON.parse(e.trim())}catch{throw new Error("Active telemetry capture returned invalid JSON")}}function cY(e){if(typeof e!="object"||e===null)throw new Error("Invalid capture payload");let t=e.telemetry;if(typeof t!="object"||t===null)throw new Error("Invalid capture telemetry");let n=t;if(n.mode!=="recent_exact_session"||typeof n.complete!="boolean")throw new Error("Recent telemetry capture is incomplete");let i=t.captured;if(!Array.isArray(i))throw new Error("Invalid capture entries");let r=i.map(a=>{if(typeof a!="object"||a===null||typeof a.captured!="boolean")throw new Error("Invalid capture entry");return{captured:a.captured}}),o=n.complete?0:n.pending_count;if(!n.complete&&(!Number.isSafeInteger(o)||o<1||!Number.isSafeInteger(n.candidate_count)||n.candidate_count<r.length+o))throw new Error("Recent telemetry capture lacks bounded pending progress");return{captured:r,complete:n.complete,pending:o}}function lY(e){return(e instanceof Error?`${e.message}
|
|
354
354
|
${"stdout"in e?String(e.stdout??""):""}
|
|
@@ -360,13 +360,13 @@ ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest
|
|
|
360
360
|
|
|
361
361
|
`;await this.write(i)}},zY=async(e,t,n)=>{try{await t(e)}catch(i){i instanceof Error&&n?(await n(i,e),await e.writeSSE({event:"error",data:i.message})):console.error(i)}finally{e.close()}},qY=new WeakMap,ly=(e,t,n)=>{let{readable:i,writable:r}=new TransformStream,o=new _C(r,i);return L_()&&e.req.raw.signal.addEventListener("abort",()=>{o.closed||o.abort()}),qY.set(o.responseReadable,e),e.header("Transfer-Encoding","chunked"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),zY(o,t,n),e.newResponse(o.responseReadable)};function pC(e,t,n=!1){let i=new Set,r;n&&(r=setTimeout(()=>process.exit(0),12e3),r.unref());let o=a=>{i.delete(a)&&(!n||i.size!==0||(r!==void 0&&clearTimeout(r),r=setTimeout(()=>process.exit(0),12e3),r.unref()))};e.get(`${t}/browser-lease`,a=>{let s={};return r!==void 0&&clearTimeout(r),r=void 0,i.add(s),ly(a,async l=>{let c,u;l.onAbort(()=>{c!==void 0&&clearTimeout(c),u?.(),o(s)});try{for(await l.writeSSE({event:"lease",data:"active"});!l.aborted;)await new Promise(d=>{u=d,c=setTimeout(d,1e4),c.unref()}),l.aborted||await l.write(`: keep-alive
|
|
362
362
|
|
|
363
|
-
`)}finally{c!==void 0&&clearTimeout(c),o(s)}})})}function D_(e,t){let n=e.length;return{tasks:M_(e.map(i=>i.task_count),n),specs:M_(e.map(i=>i.spec_count),n),prds:M_(e.map(i=>i.prd_count),n),durationMs:M_(e.map(i=>i.duration_ms),n),tokens:mC(e.map(i=>i.total_tokens)),cost:mC(e.map(i=>t==="BRL"?i.estimated_brl:i.estimated_usd))}}function mC(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function M_(e,t){return t===0||e.every(n=>n===null)?null:e.reduce((n,i)=>n+(i??0),0)/t}zn();Ma();function GC(e,t){let n=new Map(e.map(i=>[i.key,i]));for(let i of t??[])n.has(i)||n.set(i,u9(i));return[...n.values()].sort((i,r)=>r.latest_started_at.localeCompare(i.latest_started_at)||i.label.localeCompare(r.label))}function u9(e){return{key:e,label:e,latest_started_at:"",run_count:0,task_count:0,prd_count:0,spec_count:0,evidence_count:0,test_count:0,event_count:0,total_tokens:0,estimated_usd:0,estimated_brl:0,duration_ms:0,duration:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},coverage:{events:0,tokens:0,usd:0,brl:0}}}function by(e){return e.length===0||e.some(t=>t===null)?null:e.reduce((t,n)=>t+(n??0),0)/e.length}function Da(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function kc(e,t="all_invocations"){let n=new Map;for(let a of e)n.has(a.run_id)||n.set(a.run_id,a);let i=[...n.values()];if(t==="all_invocations")return i;let r=new Set(i.map(a=>a.run_id));return t==="all_execution"?i.filter(a=>a.phase==="execution"):i.filter(a=>a.phase==="execution"&&(a.parent_run_id===null||!r.has(a.parent_run_id)))}function q_(e,t="all_invocations"){let n=kc(e,t),i=n.filter(o=>o.duration_ms!==null),r=n.length-i.length;return{known_sum:i.reduce((o,a)=>o+a.duration_ms,0),unknown:r,complete:r===0,coverage_ratio:n.length===0?1:i.length/n.length}}function V_(e){let t=e?.trim().toLowerCase();return!t||t==="unknown"||t==="codex"?"openai":t}var d9={events:0,tokens:0,usd:0,brl:0};function XC(e,t){let n=new Map;for(let l of t)l.task_id!==null&&n.set(l.task_id,[...n.get(l.task_id)??[],l]);let i=e.filter(l=>n.has(l.id)).map(l=>YC(l,n.get(l.id)??[])),r=new Set(e.map(l=>l.id)),o=[...n].filter(([l])=>!r.has(l)).map(([l,c])=>KC(l,c)),a=t.filter(l=>l.task_id===null),s=a.length===0?[]:[KC("Sem tarefa vinculada",a)];return[...i,...o,...s].sort((l,c)=>c.latest_started_at.localeCompare(l.latest_started_at))}function KC(e,t){return{...YC({id:e,title:e,created_at:t[0]?.started_at??"",test_count:0},t),label:`Tarefa hist\xF3rica: ${e}`,latest_started_at:t.reduce((n,i)=>i.started_at>n?i.started_at:n,"")}}function YC(e,t){let n=q_(t);return{key:e.id,label:e.title,latest_started_at:e.created_at,run_count:t.length,task_count:1,tasksCreated:1,tasksActive:1,prd_count:0,spec_count:0,evidence_count:0,test_count:e.test_count??0,event_count:t.reduce((i,r)=>i+(r.event_count??0),0),total_tokens:Da(t.map(i=>i.total_tokens)),estimated_usd:Da(t.map(i=>i.estimated_usd)),estimated_brl:Da(t.map(i=>i.estimated_brl)),duration_ms:n.known_sum,duration:n,coverage:t.reduce((i,r)=>({events:i.events+r.coverage.events,tokens:i.tokens+r.coverage.tokens,usd:i.usd+r.coverage.usd,brl:i.brl+r.coverage.brl}),d9),coverage_counts:{source:"run_rows",granularity:"event",events:t.reduce((i,r)=>i+r.coverage.events,0),tokens:null,usd:null,brl:null,metrics:{tokens:Sy(t,i=>i.total_tokens),usd:Sy(t,i=>i.estimated_usd),brl:Sy(t,i=>i.estimated_brl)}}}}function Sy(e,t){let n=e.filter(i=>t(i)!==null).length;return{eligible_runs:e.length,known_runs:n,unknown_runs:e.length-n}}function ja(e,t,n=r=>r,i="all_invocations"){let r=[...new Set(e.map(t).filter(a=>a!==null))],o=new Set(kc(e,i).map(a=>a.run_id));return r.map(a=>{let s=e.filter(c=>t(c)===a),l=q_(s.filter(c=>o.has(c.run_id)),i);return{key:a,label:n(a),latest_started_at:s.reduce((c,u)=>u.started_at>c?u.started_at:c,s[0]?.started_at??""),run_count:s.length,task_count:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,tasksActive:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,taskDaysActive:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,prd_count:0,spec_count:0,evidence_count:0,test_count:0,event_count:s.reduce((c,u)=>c+(u.event_count??0),0),total_tokens:ky(s.map(c=>c.total_tokens)),estimated_usd:ky(s.map(c=>c.estimated_usd)),estimated_brl:ky(s.map(c=>c.estimated_brl)),duration_ms:l.known_sum,duration:l,coverage:_9(s)}}).sort(p9)}function ky(e){return Da(e)}function QC(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function _9(e){return e.reduce((t,n)=>({events:t.events+n.coverage.events,tokens:t.tokens+n.coverage.tokens,usd:t.usd+n.coverage.usd,brl:t.brl+n.coverage.brl}),{events:0,tokens:0,usd:0,brl:0})}function p9(e,t){return t.latest_started_at.localeCompare(e.latest_started_at)}function W_(e,t,n){if(e.schema_version!==2)throw new TypeError("Cost Monitor accepts only OperationsProjection V2");let i=t?.currency??"BRL",r=ni(n?.agentNames??[]),o=e.runs,a=new Map(e.runs.map(h=>[h.id,h])),s=o,l=s,c=new Map(e.tasks.map(h=>[h.id,h])),d=l.map(h=>{let k=h.task_id===null?void 0:c.get(h.task_id),P=a.get(h.id),U=P?.usage.total.cost??{usd:null,brl:null},$=(P?.pricing_segments??[]).map(Q=>Q.recorded_fx_rate??nI(Q.recorded_usd??null,Q.recorded_brl??null)).filter(Q=>Q!==null),B=h.usage.total,z=B.coverage.tokens>0,R=B.coverage.usd>0,L=B.coverage.brl>0,J=t?g9(h,t):null,le=z?oI(P?.usage.total.tokens??B.tokens):null,j=k9(h);return{run_id:h.id,execution_id:h.execution_id,conversation_id:h.conversation_id,task_id:h.task_id,task_title:k?.title??h.task_id??h.conversation_id??h.id,task_status:k?.status??h.status,priority:k?.priority??"none",risk:k?.risk??"none",spec_id:h.spec_id,prd_id:h.prd_id,change_id:h.change_id,parent_run_id:h.parent_run_id,run_role:h.run_role,run_kind:h.run_kind,run_purpose:h.run_purpose,requires_finalizer:h.requires_finalizer,client:h.client,agent:h.agent,agent_name:f9(h,n),provider:V_(h.provider),model:h.effective_model??h.model,requested_model:h.model,reasoning_effort:h.reasoning_effort??null,effective_reasoning_effort:h.effective_reasoning_effort,service_tier:h.service_tier??null,call_count:h.call_count,status:h.status,phase:m9(h),origin:h.entrypoint,work_type:h.work_type,started_at:h.started_at,finished_at:h.finished_at,...j,estimation_basis:null,source_started_at:h.source_started_at??null,source_finished_at:h.source_finished_at??null,capture_lag_ms:h.capture_lag_ms??null,event_count:B.events,input_tokens:B.tokens.input,cached_input_tokens:B.tokens.cached_input,output_tokens:B.tokens.output,reasoning_tokens:B.tokens.reasoning,total_tokens:le,uncached_input_tokens:B.tokens.input===null?null:Math.max(B.tokens.input-(B.tokens.cached_input??0),0),visible_output_tokens:B.tokens.output===null?null:Math.max(B.tokens.output-(B.tokens.reasoning??0),0),input_rate_usd_per_million:J?.rates.input??null,cached_input_rate_usd_per_million:J?.rates.cached??null,output_rate_usd_per_million:J?.rates.output??null,reasoning_rate_usd_per_million:J?.rates.reasoning??null,context_input_multiplier:J?.context.input??null,context_output_multiplier:J?.context.output??null,speed_cost_multiplier:J?.speedMultiplier??null,standard_cost_usd:J?.standardUsd??null,speed_uplift_usd:J?.upliftUsd??null,input_cost_usd:J?.components.input??null,cached_input_cost_usd:J?.components.cached??null,output_cost_usd:J?.components.output??null,reasoning_cost_usd:J?.components.reasoning??null,fx_rate:i==="BRL"?t?.fxRate?.rate??null:null,estimated_usd:R?U.usd:null,estimated_brl:L?U.brl:null,recorded_usd:R?U.usd:null,recorded_brl:L?U.brl:null,recorded_fx_rate:S9($)??nI(U.usd,U.brl),coverage:B.coverage,artifact_path:h.artifact_path}}),_=(h,k,P)=>ja(d,h,k,P),p=eo(s),g={conversation:eo(s.filter(h=>h.entrypoint==="conversation")),task:eo(s.filter(h=>h.entrypoint==="task")),spec:eo(s.filter(h=>h.entrypoint==="spec")),prd:eo(s.filter(h=>h.entrypoint==="prd"))},m=p.total,f=d.filter(h=>h.total_tokens!==null),v=f.reduce((h,k)=>h+(k.total_tokens??0),0),S=f.reduce((h,k)=>h+(k.event_count??0),0),b=[...f].sort((h,k)=>(k.total_tokens??0)-(h.total_tokens??0)).slice(0,10).reduce((h,k)=>h+(k.total_tokens??0),0);return{schema_version:2,layout_version:2,readonly:!0,legacy_effort_baseline:{cutoff:gn.cutoff,duration_ms:gn.durationMs},source:e.source,currency:i,pricing:{catalog_updated_at:t?.catalog.updated_at??null,fx_rate:i==="BRL"?t?.fxRate?.rate??null:null,conversion_applied:t!==void 0&&i==="BRL"&&t.fxRate!==null},filters:e.filters,overview:{task_count:new Set(d.flatMap(h=>h.task_id===null?[]:[h.task_id])).size,run_count:d.length,event_count:d.reduce((h,k)=>h+(k.event_count??0),0),total_tokens:m.tokens.total,estimated_usd:m.cost.usd,estimated_brl:m.cost.brl,recorded_usd:tI(s.map(h=>a.get(h.id)?.usage.total.cost.usd??null)),recorded_brl:tI(s.map(h=>a.get(h.id)?.usage.total.cost.brl??null)),average_run_cost_usd:by(d.map(h=>h.estimated_usd)),average_run_cost_brl:by(d.map(h=>h.estimated_brl)),average_run_duration_ms:QC(kc(d).map(h=>h.duration_ms)),known_tokens_per_cycle:S===0?null:v/S,top_10_token_share:v===0?null:b/v,coverage:m.coverage},filters_available:{providers:ni(d.map(h=>V_(h.provider))),agents:ni(d.map(h=>h.agent_name)),models:ni(d.map(h=>h.model)),statuses:ni(d.map(h=>h.task_status)),priorities:ni(d.map(h=>h.priority)),risks:ni(d.map(h=>h.risk)),phases:ni(d.map(h=>h.phase)),origins:ni(d.map(h=>h.origin)),work_types:ni(d.map(h=>h.work_type))},configured_agents:r,usage:p,origins:g,prds:rI(e.prds,s),specs:rI(e.specs,s),runs:[...d].sort((h,k)=>k.started_at.localeCompare(h.started_at)),groups:{conversations:ja(d,h=>h.conversation_id,void 0,"all_invocations"),tasks:XC(e.tasks,d),providers:_(h=>V_(h.provider)),agents:GC(_(h=>h.agent_name),r),models:_(h=>h.model),daily:wy(ja(d,h=>{let k=h.finished_at??h.started_at;return Wt(k,"day")??k.slice(0,10)},void 0,"all_invocations"),e.tasks,"day"),monthly:wy(ja(d,h=>{let k=h.finished_at??h.started_at;return Wt(k,"month")??k.slice(0,7)},void 0,"all_invocations"),e.tasks,"month"),annual:wy(ja(d,h=>{let k=h.finished_at??h.started_at;return Wt(k,"year")??k.slice(0,4)},void 0,"all_invocations"),e.tasks,"year")}}}function wy(e,t,n){let i=new Map(e.map(r=>[r.key,{...r,tasksActive:r.tasksActive??r.task_count,taskDaysActive:r.tasksActive??r.task_count,tasksCreated:0}]));for(let r of t){let o=Wt(r.created_at,n);if(o===null)continue;let a=i.get(o);a!==void 0&&(a.tasksCreated=(a.tasksCreated??0)+1)}return[...i.values()]}function m9(e){return e.entrypoint==="task"&&e.phase==="conversation"?"planning":e.phase}function f9(e,t){if(e.agent==="codex")return"codex";let n=t?.agentNamesById?.[e.agent];if(n!==void 0)return n;if(e.agent==="agent-orchestrator")return t?.agentNamesByRole?.orchestrator??"zaip-agent-orchestrator";if(e.agent_name.trim()===e.agent){let i=t?.agentNamesByRole?.[e.run_role];if(i!==void 0)return i}return e.agent_name!=="codex",e.agent_name}function g9(e,t){let n=e.pricing_segments??[],i=n.length>0?n.map(m=>({provider:m.provider,model:m.model??e.effective_model??e.model,serviceTier:m.service_tier??e.service_tier??"default",usage:v9(m)})):[{provider:e.provider,model:e.effective_model??e.model,serviceTier:e.service_tier??"default",usage:b9(e.usage.total)}],r=i.map(m=>Mo({provider:m.provider==="openai"||m.provider==="anthropic"?m.provider:null,model:m.model,serviceTier:m.serviceTier,usage:m.usage,catalog:t.catalog,fxRate:null})),o=i.map(m=>Mo({provider:m.provider==="openai"||m.provider==="anthropic"?m.provider:null,model:m.model,serviceTier:"default",usage:m.usage,catalog:t.catalog,fxRate:null})),a=eI(r.map(m=>m.estimated_usd)),s=eI(o.map(m=>m.estimated_usd)),l=a,c=l===null&&s!==null,u=h9(i,t.catalog),d=y9(t.catalog,i.map(m=>m.model)),_=i.some(m=>m.serviceTier==="priority"||m.serviceTier==="fast"),p=(m,f)=>_&&!c?f:m,g=i.some(m=>d?.long_context_threshold_tokens!==null&&d?.long_context_threshold_tokens!==void 0&&(m.usage.input??0)>d.long_context_threshold_tokens);return{rates:{input:d?p(d.input_per_million_usd,d.priority_input_per_million_usd??null):null,cached:d?p(d.cached_input_per_million_usd,d.priority_cached_input_per_million_usd??null):null,output:d?p(d.output_per_million_usd,d.priority_output_per_million_usd??null):null,reasoning:d?p(d.reasoning_per_million_usd??d.output_per_million_usd,d.priority_reasoning_per_million_usd??d.priority_output_per_million_usd??null):null},context:{input:d?g?d.long_context_input_multiplier:1:null,output:d?g?d.long_context_output_multiplier:1:null},speedMultiplier:l!==null&&s!==null&&s>0?Math.round(l/s*1e3)/1e3:null,standardUsd:s,upliftUsd:l!==null&&s!==null?B_(l-s):null,components:{input:u?.input??null,cached:u?.cached??null,output:u?.output??null,reasoning:u?.reasoning??null}}}function h9(e,t){let n=0,i=0,r=0;for(let o of e){let a=iI(t,o.model);if(a===null||o.provider!==null&&o.provider!==a.provider||o.usage.input===null||o.usage.cached_input===null||o.usage.output===null)return null;let s=a.long_context_threshold_tokens!==null&&o.usage.input>a.long_context_threshold_tokens,l=o.serviceTier==="priority"||o.serviceTier==="fast",c=a.priority_input_per_million_usd,u=a.priority_output_per_million_usd,d=l&&!s&&c!==null&&c!==void 0&&u!==null&&u!==void 0,_=d&&c!==null&&c!==void 0?c:a.input_per_million_usd,p=d?a.priority_cached_input_per_million_usd??0:a.cached_input_per_million_usd??0,g=d&&u!==null&&u!==void 0?u:a.output_per_million_usd,m=s?a.long_context_input_multiplier:1,f=s?a.long_context_output_multiplier:1,v=Math.max(o.usage.input-o.usage.cached_input,0);n+=v/1e6*_*m,i+=o.usage.cached_input/1e6*p*m,r+=o.usage.output/1e6*g*f}return{input:n,cached:i,output:r,reasoning:0}}function iI(e,t){let n=t.toLowerCase();return e.models.find(i=>i.id.toLowerCase()===n||i.aliases.some(r=>r.toLowerCase()===n))??null}function y9(e,t){let n=t.map(r=>iI(e,r));if(n.some(r=>r===null))return null;let i=n[0];return!i||n.some(r=>r?.id!==i.id)?null:i}function v9(e){return{input:e.input_tokens,cached_input:e.cached_input_tokens,output:e.output_tokens,reasoning:e.reasoning_tokens,total:e.total_tokens,source:"provider_reported"}}function b9(e){return{input:e.tokens.input,cached_input:e.tokens.cached_input,output:e.tokens.output,reasoning:e.tokens.reasoning,total:e.tokens.total,source:"provider_reported"}}function eI(e){return e.length===0||e.some(t=>t===null)?null:B_(e.reduce((t,n)=>t+n,0))}function tI(e){let t=e.filter(n=>n!==null);return t.length===0?null:B_(t.reduce((n,i)=>n+i,0))}function B_(e){return Math.round(e*1e6)/1e6}function nI(e,t){return e!==null&&e>0&&t!==null?B_(t/e):null}function S9(e){if(e.length===0)return null;let t=e[0]??null;return e.every(n=>n===t)?t:null}function k9(e){return typeof e.source_duration_ms=="number"&&e.source_duration_ms>=0?{duration_ms:e.source_duration_ms,duration_provenance:"observed"}:typeof e.duration_ms=="number"&&e.duration_ms>=0&&(e.duration_provenance===void 0||e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")?{duration_ms:e.duration_ms,duration_provenance:e.duration_provenance??"legacy_inferred"}:{duration_ms:null,duration_provenance:"unavailable"}}function eo(e){return Object.fromEntries(["conversation","planning","execution","total","new_work","rework"].map(n=>[n,w9(e.map(i=>i.usage[n]))]))}function w9(e){let t=n=>{let i=n.filter(r=>r!==null);return i.length===0?null:i.reduce((r,o)=>r+o,0)};return{events:e.reduce((n,i)=>n+i.events,0),duration_ms:t(e.map(n=>n.duration_ms??null)),tokens:{input:t(e.map(n=>n.tokens.input)),cached_input:t(e.map(n=>n.tokens.cached_input)),output:t(e.map(n=>n.tokens.output)),reasoning:t(e.map(n=>n.tokens.reasoning)),total:t(e.map(n=>oI(n.tokens)))},cost:{usd:t(e.map(n=>n.cost.usd)),brl:t(e.map(n=>n.cost.brl))},coverage:{events:e.reduce((n,i)=>n+i.coverage.events,0),tokens:e.reduce((n,i)=>n+i.coverage.tokens,0),usd:e.reduce((n,i)=>n+i.coverage.usd,0),brl:e.reduce((n,i)=>n+i.coverage.brl,0)}}}function oI(e){return e.input!==null&&e.output!==null?e.input+e.output:e.total}function rI(e,t){return e.map(n=>{let i=new Set(n.run_ids),r=t.filter(o=>i.has(o.id)||n.kind==="prd"&&o.prd_id===n.id||n.kind==="spec"&&o.spec_id===n.id);return{...n,usage:eo(r)}})}function ni(e){return[...new Set(e)].sort()}Ma();ea();function is(){return{events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}}}function XP(){let e=()=>({conversation:is(),planning:is(),execution:is(),total:is(),new_work:is(),rework:is()});return{conversation:e(),task:e(),spec:e(),prd:e()}}function Gp(e,t,n,i){let r=(e.run_metrics??[]).map(bQ),o=r.filter(z=>{let R=Wt(z.finished_at??z.started_at,"day");return R!==null&&QP(R,t.filters.from,t.filters.to)}).map(vQ),a=t.schema_version===2?W_({...t,tasks:t.tasks??[],runs:o},void 0):null,s=z=>z.filter(R=>{let L=R.key.trim().toLowerCase();return L.length>0&&!["mixed","unknown","unavailable"].includes(L)}),l=e.run_metrics!==void 0,c=e.cost_monitor_daily_duration!==void 0||e.canonical_daily_duration_ms!==void 0,u=new Map(Object.entries(SQ(e)));for(let z of Object.keys(e.cost_monitor_daily_duration??{}))u.has(z)||u.set(z,xb());if(!l&&!c)for(let z of Object.keys(ti))u.has(z)||u.set(z,xb());let d=[...u].filter(([z])=>QP(z,t.filters.from,t.filters.to)),_=wQ(r),p=e.cost_monitor_daily_duration,g=(z,R)=>{if(p!==void 0){let L=p[z];return L===void 0?Eb():{value:{known_sum:L.known_sum,unknown:L.eligible_runs-L.known_runs,complete:L.eligible_runs===L.known_runs,coverage_ratio:L.eligible_runs===0?1:L.known_runs/L.eligible_runs},population:ai(L.eligible_runs,L.known_runs)}}if(e.canonical_daily_duration_ms!==void 0){let L=e.canonical_daily_duration_ms[z];return L===void 0?Eb():{value:{known_sum:L,unknown:0,complete:!0,coverage_ratio:1},population:ai(R.runs,R.runs)}}return l?_.get(z)??Eb():yQ(z,R)},m=new Map((e.daily_rows??[]).map(z=>[z.key,z])),v=d.map(([z,R])=>kQ(z,R,i,g(z,R),m.get(z))),S=v.reduce((z,R)=>z+R.run_count,0),b=v.reduce((z,R)=>z+R.event_count,0),h=!c&&o.every(z=>z.usage.total.tokens.total===null)?null:Ab(v.map(z=>z.total_tokens)),k=!c&&o.every(z=>z.usage.total.cost.brl===null)?null:Ab(v.map(z=>z.estimated_brl)),P=Ab(v.map(z=>z.estimated_usd)),U=EQ(e.run_metrics??[]),$=t.summary.overview_metrics?.task_count??t.summary.task_count,B={events:S,tokens:v.reduce((z,R)=>z+R.coverage.tokens,0),usd:v.reduce((z,R)=>z+R.coverage.usd,0),brl:v.reduce((z,R)=>z+R.coverage.brl,0)};return{schema_version:2,layout_version:t.layout_version,readonly:!0,source:".agents/records",aggregate_only:!0,data_source:l||c?"run_records":"lifecycle_manifest_summary",legacy_effort_baseline:!l&&!c&&t.filters.from===null&&t.filters.to===null?{cutoff:gn.cutoff,duration_ms:gn.durationMs}:null,currency:n,pricing:{catalog_updated_at:null,fx_rate:i,conversion_applied:i!==null},filters:t.filters,overview:{task_count:$,run_count:S,event_count:b,total_tokens:h,estimated_usd:P,estimated_brl:k,recorded_usd:null,recorded_brl:null,average_run_cost_usd:S===0||P===null||B.usd!==S?null:P/S,average_run_cost_brl:S===0||k===null||B.brl!==S?null:k/S,average_run_duration_ms:U,known_tokens_per_cycle:S===0||h===null?null:h/S,top_10_token_share:null,coverage:B},filters_available:{providers:e.filters_available?.providers??a?.filters_available.providers??[],agents:e.filters_available?.agents??a?.filters_available.agents??[],models:e.filters_available?.models??a?.filters_available.models??[],statuses:e.filters_available?.statuses??a?.filters_available.statuses??[],priorities:e.filters_available?.priorities??a?.filters_available.priorities??[],risks:e.filters_available?.risks??a?.filters_available.risks??[],phases:e.filters_available?.phases??a?.filters_available.phases??[],origins:e.filters_available?.origins??a?.filters_available.origins??[],work_types:e.filters_available?.work_types??a?.filters_available.work_types??[]},configured_agents:a?.configured_agents??[],usage:e.aggregate_usage??a?.usage??eo(o),origins:XP(),prds:a?.prds??t.prds,specs:a?.specs??t.specs,runs:[],groups:{conversations:[],tasks:[],providers:s(a?.groups.providers??[]),agents:a?.groups.agents??[],models:s(e.model_groups??a?.groups.models??[]),daily:v,monthly:YP(v,7),annual:YP(v,4)}}}function yQ(e,t){if((ti[e]??0)>0)return Yo(e,t);if(t.duration!==void 0){let n=Rb(t.runs,t.duration.unknown);return{value:t.duration,population:ai(t.runs,n)}}return{value:{known_sum:0,unknown:t.runs,complete:t.runs===0,coverage_ratio:t.runs===0?1:0},population:ai(t.runs,0)}}function xb(){let e={known_sum:0,unknown:0,complete:!0,coverage_ratio:1};return{prds:0,specs:0,tasks:0,validations:0,evidences:0,runs:0,usage:{total_tokens:e,cost:{...e,currency:"BRL"}}}}function vQ(e){let t={events:0,duration_ms:null,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},n={...t,events:e.events??0,duration_ms:e.source_duration_ms??null,tokens:{...t.tokens,input:e.input_tokens??null,cached_input:e.cached_input_tokens??null,output:e.output_tokens??null,reasoning:e.reasoning_tokens??null,total:e.total_tokens},cost:{usd:null,brl:e.currency==="BRL"?e.cost:null},coverage:{events:e.events??0,tokens:e.total_tokens===null?0:1,usd:0,brl:e.cost===null?0:1}},i=e.phase==="conversation"||e.phase==="planning"?e.phase:"execution";return{id:e.id,artifact_path:`.agents/records/runs/${e.id}`,status:e.status==="failed"||e.status==="cancelled"||e.status==="running"?e.status:"completed",phase:i,entrypoint:e.entrypoint==="observation"?"observation":e.task_id===null?"conversation":"task",work_type:"new",run_role:e.run_kind==="subrun"?"subagent":"orchestrator",run_kind:e.run_kind??"run",run_purpose:e.run_purpose==="observation"?"observation":"execution",requires_finalizer:!1,parent_run_id:e.parent_run_id,client:"unknown",agent:e.agent??"unknown",agent_name:e.agent_name??e.agent??"unknown",provider:e.provider??"unavailable",model:e.model??"unknown",reasoning_effort:null,effective_model:e.model??null,effective_reasoning_effort:null,effective_config_mixed:!1,call_count:null,terminal_call_count:null,failed_call_count:0,cancelled_call_count:0,conversation_id:e.entrypoint==="observation"?null:e.conversation_id??e.id,execution_id:e.execution_id??null,task_id:e.task_id,spec_id:e.spec_id??null,prd_id:e.prd_id??null,change_id:e.change_id??null,started_at:e.started_at,finished_at:e.finished_at,duration_ms:e.duration_ms,source_duration_ms:e.source_duration_ms??null,...e.duration_provenance===void 0?{}:{duration_provenance:e.duration_provenance},...e.estimation_basis===void 0?{}:{estimation_basis:e.estimation_basis},usage:{conversation:i==="conversation"?n:t,planning:i==="planning"?n:t,execution:i==="execution"?n:t,total:n,new_work:n,rework:t}}}function bQ(e){let t=e.source_duration_ms??e.duration_ms,n=e.source_duration_ms!==null&&e.source_duration_ms!==void 0?"observed":e.duration_provenance??"legacy_inferred";return typeof t=="number"&&t>=0&&(n==="observed"||n==="reconciled"||n==="legacy_inferred")?{...e,duration_ms:t,duration_provenance:n,estimation_basis:null}:{...e,duration_ms:null,duration_provenance:"unavailable",estimation_basis:null}}function SQ(e){let t=[...new Map((e.run_metrics??[]).map(r=>[r.id,r])).values()];if(e.run_metrics===void 0)return e.periods.daily;let n=new Map;for(let r of t){let o=Wt(r.started_at,"day");o!==null&&n.set(o,[...n.get(o)??[],r])}let i=new Set([...Object.keys(e.periods.daily),...n.keys()]);return Object.fromEntries([...i].map(r=>{let o=e.periods.daily[r]??xb(),a=n.get(r)??[],s=kb(a.map(u=>u.total_tokens)),l=kb(a.map(u=>u.cost)),c=kb(a.map(u=>u.events));return[r,{...o,runs:a.length,usage:{total_tokens:s,cost:{...l,currency:a.find(u=>u.currency!==null)?.currency??o.usage.cost.currency}},events:c}]}))}function kb(e){let t=e.filter(i=>i!==null),n=e.length-t.length;return{known_sum:t.reduce((i,r)=>i+r,0),unknown:n,complete:n===0,coverage_ratio:e.length===0?1:t.length/e.length}}function kQ(e,t,n,i,r){let o=t.usage.cost.known_sum===0&&t.usage.cost.unknown>0?null:t.usage.cost.known_sum,a=r===void 0?o:r.total_cost_brl,s=r===void 0?a!==null&&n!==null&&n>0?a/n:null:r.total_cost_usd,l=t.events?.known_sum??0,c=Rb(t.runs,t.usage.total_tokens.unknown),u=Rb(t.runs,t.usage.cost.unknown);return{key:e,label:e,latest_started_at:`${e}T23:59:59.999-03:00`,run_count:t.runs,task_count:t.tasks,tasksCreated:t.tasks,tasksActive:t.tasks,taskDaysActive:t.tasks,prd_count:t.prds,spec_count:t.specs,evidence_count:t.evidences,test_count:t.validations,event_count:l,total_tokens:t.usage.total_tokens.known_sum===0&&t.usage.total_tokens.unknown>0?null:t.usage.total_tokens.known_sum,estimated_usd:s,estimated_brl:a,duration_ms:i.population.known_runs>0?i.value.known_sum:null,duration:i.value,coverage:{events:t.runs,tokens:c,usd:u,brl:u},coverage_counts:{source:"period_summary",granularity:t.events===void 0?"unavailable":"event",events:t.events?.known_sum??null,tokens:null,usd:null,brl:null,metrics:{duration:i.population,tokens:ai(t.runs,c),usd:ai(t.runs,u),brl:ai(t.runs,u)}}}}function YP(e,t){let n=new Map;for(let i of e){let r=i.key.slice(0,t);n.set(r,[...n.get(r)??[],i])}return[...n].map(([i,r])=>{let o=r[0],a=r.reduce((d,_)=>d+_.duration.known_sum,0),s=r.reduce((d,_)=>d+_.duration.unknown,0),l=r.reduce((d,_)=>d+(_.coverage_counts?.metrics?.duration?.eligible_runs??0),0),c=r.reduce((d,_)=>d+(_.coverage_counts?.metrics?.duration?.known_runs??0),0),u=r.reduce((d,_)=>d+_.run_count,0);return{...o,key:i,label:i,latest_started_at:r.map(d=>d.latest_started_at).sort().at(-1)??o.latest_started_at,run_count:u,task_count:r.reduce((d,_)=>d+(_.task_count??0),0),tasksCreated:r.reduce((d,_)=>d+(_.tasksCreated??0),0),tasksActive:r.reduce((d,_)=>d+(_.tasksActive??0),0),taskDaysActive:r.reduce((d,_)=>d+(_.taskDaysActive??0),0),prd_count:r.reduce((d,_)=>d+(_.prd_count??0),0),spec_count:r.reduce((d,_)=>d+(_.spec_count??0),0),evidence_count:r.reduce((d,_)=>d+(_.evidence_count??0),0),test_count:r.reduce((d,_)=>d+(_.test_count??0),0),event_count:r.reduce((d,_)=>d+_.event_count,0),total_tokens:Tb(r.map(d=>d.total_tokens)),estimated_usd:Tb(r.map(d=>d.estimated_usd)),estimated_brl:Tb(r.map(d=>d.estimated_brl)),duration_ms:s===0?a:null,duration:{known_sum:a,unknown:s,complete:s===0,coverage_ratio:l===0?1:c/l},coverage:{events:r.reduce((d,_)=>d+_.coverage.events,0),tokens:r.reduce((d,_)=>d+_.coverage.tokens,0),usd:r.reduce((d,_)=>d+_.coverage.usd,0),brl:r.reduce((d,_)=>d+_.coverage.brl,0)},...o.coverage_counts===void 0?{}:{coverage_counts:{...o.coverage_counts,metrics:{duration:ai(l,c),tokens:wb(r,"tokens"),usd:wb(r,"usd"),brl:wb(r,"brl")}}}}}).sort((i,r)=>r.key.localeCompare(i.key))}function wb(e,t){let n=e.map(i=>i.coverage_counts?.metrics?.[t]);return ai(n.reduce((i,r)=>i+(r?.eligible_runs??0),0),n.reduce((i,r)=>i+(r?.known_runs??0),0))}function wQ(e){return el(e)}function EQ(e){let t=e.filter(n=>n.phase==="execution"&&n.parent_run_id==null&&z_(n.duration_started_at??n.started_at)&&n.duration_ms!==null&&n.duration_ms>=0);return t.length===0?null:t.reduce((n,i)=>n+i.duration_ms,0)/t.length}function Eb(){return{value:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},population:ai(0,0)}}function QP(e,t,n){let i=a=>a===null?null:/^\d{4}-\d{2}-\d{2}$/.test(a)?a:Wt(a,"day"),r=i(t),o=i(n);return(r===null||e>=r)&&(o===null||e<=o)}function Ab(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function Tb(e){return e.some(t=>t===null)?null:e.reduce((t,n)=>t+(n??0),0)}function Rb(e,t){return Math.max(0,e-t)}function ai(e,t){return{eligible_runs:e,known_runs:t,unknown_runs:e-t}}zn();function Et(e){let t=e.req.query("from")??null,n=e.req.query("to")??null;return{from:e$(t,"start"),to:e$(n,"end")}}function e$(e,t){if(e===null||!/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let n=t$(e);if(t==="start")return new Date(n).toISOString();let[i,r,o]=e.split("-").map(Number),a=new Date(Date.UTC(i,r-1,o+1)).toISOString().slice(0,10);return new Date(t$(a)-1).toISOString()}function t$(e){let[t,n,i]=e.split("-").map(Number),r=Date.UTC(t,n-1,i),o=r-n$(r);return o=r-n$(o),o}function n$(e){let n=new Intl.DateTimeFormat("en-US",{timeZone:"America/Sao_Paulo",timeZoneName:"longOffset"}).formatToParts(new Date(e)).find(o=>o.type==="timeZoneName")?.value??"GMT",i=/^GMT([+-])(\d{2}):(\d{2})$/.exec(n);if(i===null)return 0;let r=Number(i[2])*60+Number(i[3]);return(i[1]==="+"?1:-1)*r*6e4}zn();ea();function ol(e,t){let n=new Map(e.map(i=>[i.id,i]));for(let i of t.map(r=>Ob(r,t))){let r=n.get(i.id);if(r===void 0){n.set(i.id,i);continue}n.set(i.id,{...i,...r,usage:AQ(r.usage,i.usage),provider:r.provider??i.provider,model:r.model==="unknown"?i.model:r.model,reasoning_effort:r.reasoning_effort??i.reasoning_effort,service_tier:r.service_tier??i.service_tier??null,call_count:r.call_count??i.call_count,terminal_call_count:r.terminal_call_count??i.terminal_call_count,...(r.pricing_segments?.length??0)>0?{pricing_segments:r.pricing_segments}:i.pricing_segments===void 0?{}:{pricing_segments:i.pricing_segments},...r.duration_ms!==null&&(r.source_duration_ms===null||r.source_duration_ms===0)?{duration_ms:r.duration_ms,source_duration_ms:null,source_started_at:null,source_finished_at:null,capture_lag_ms:null}:TQ(r)})}return[...n.values()]}function AQ(e,t){let n=(i,r)=>({...r,...i,tokens:{...r.tokens,...i.tokens,input:i.tokens.input??r.tokens.input,cached_input:i.tokens.cached_input??r.tokens.cached_input,output:i.tokens.output??r.tokens.output,reasoning:i.tokens.reasoning??r.tokens.reasoning,total:i.tokens.total??r.tokens.total},cost:{...r.cost,...i.cost,usd:i.cost.usd??r.cost.usd,brl:i.cost.brl??r.cost.brl}});return{conversation:n(e.conversation,t.conversation),planning:n(e.planning,t.planning),execution:n(e.execution,t.execution),total:n(e.total,t.total),new_work:n(e.new_work,t.new_work),rework:n(e.rework,t.rework)}}function TQ(e){return{duration_ms:e.duration_ms,...typeof e.source_duration_ms=="number"?{duration_provenance:"observed"}:e.duration_provenance===void 0?{}:{duration_provenance:e.duration_provenance},estimation_basis:typeof e.source_duration_ms=="number"?null:e.estimation_basis??null,source_duration_ms:e.source_duration_ms??null,source_started_at:e.source_started_at??null,source_finished_at:e.source_finished_at??null,capture_lag_ms:e.capture_lag_ms??null}}function Ob(e,t){let n=Array.isArray(e.usage_segments)?e.usage_segments:[],i=d=>n.length===0||n.some(_=>!RQ(_.tokens?.[d]))?null:n.reduce((_,p)=>_+(p.tokens?.[d]??0),0),r=e.quantitative_metrics.tokens_total,o=e.quantitative_metrics.estimated_usd,a=e.quantitative_metrics.estimated_brl,s={events:e.source_event_count,tokens:{input:i("input"),cached_input:i("cached_input"),output:i("output"),reasoning:i("reasoning"),total:r.known_sum},cost:{usd:e.historical_cost?.estimated_usd??o.known_sum,brl:e.historical_cost?.estimated_brl??a.known_sum},coverage:{events:e.source_event_count,tokens:r.complete,usd:o.complete,brl:a.complete}},l={...s,events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},c=e.phase==="execution"?s:l,u=e.invocation_kind==="delegated";return{id:e.run_id,artifact_path:`.agents/records/runs/${e.run_id}`,status:e.status??"completed",phase:e.phase??"execution",entrypoint:e.purpose==="observation"?"observation":e.task_id===null?"conversation":"task",work_type:"new",run_role:u?"subagent":"orchestrator",run_kind:u?"subrun":"run",run_purpose:xQ(e.purpose,u),requires_finalizer:!1,parent_run_id:t.find(d=>d.agent_invocation_id===e.parent_agent_invocation_id)?.run_id??null,client:"codex",agent:e.zaip_agent??"unknown",agent_name:e.zaip_agent??"unknown",provider:n.find(d=>typeof d.provider=="string")?.provider??null,model:n.find(d=>typeof d.model=="string")?.model??"unknown",reasoning_effort:n.find(d=>typeof d.reasoning_effort=="string")?.reasoning_effort??null,effective_model:null,effective_reasoning_effort:null,effective_config_mixed:!1,service_tier:n.find(d=>typeof d.service_tier=="string")?.service_tier??null,call_count:e.llm_call_count,terminal_call_count:e.llm_call_count,failed_call_count:e.status==="failed"?e.llm_call_count:0,cancelled_call_count:e.status==="cancelled"?e.llm_call_count:0,conversation_id:e.purpose==="observation"?null:e.agent_invocation_id,execution_id:e.execution_id,task_id:e.task_id,spec_id:e.spec_id,prd_id:e.prd_id,change_id:e.change_id,started_at:e.occurred_at,finished_at:e.status===null?null:e.occurred_at,duration_ms:e.time.duration_ms,source_duration_ms:e.time.duration_ms,source_started_at:null,source_finished_at:e.time.source_latest_at,pricing_segments:n.map(d=>({phase:"execution",provider:d.provider,model:d.model,service_tier:d.service_tier,input_tokens:d.tokens?.input??null,cached_input_tokens:d.tokens?.cached_input??null,output_tokens:d.tokens?.output??null,reasoning_tokens:d.tokens?.reasoning??null,total_tokens:d.tokens?.total??null})),usage:{conversation:l,planning:l,execution:c,total:s,new_work:s,rework:l}}}function xQ(e,t){return e==="observation"||e==="intake"||e==="orchestration"||e==="execution"||e==="review"||e==="audit"||e==="finalization"?e:t?"execution":"orchestration"}function RQ(e){return typeof e=="number"&&Number.isFinite(e)}function r$(e,t,n){let i=t.trim().toLowerCase();if(!i)return[...e];let r=new Map(n.map(o=>[o.id,o.title]));return e.filter(o=>[o.id,o.task_id,o.task_id===null?null:r.get(o.task_id),o.provider,o.agent,o.agent_name,o.model,o.phase,o.spec_id,o.prd_id,o.execution_id,o.conversation_id].some(a=>a?.toLowerCase().includes(i)))}qe();zn();function Jn(e){return e.req.query("currency")==="USD"?"USD":"BRL"}function tt(e,t){let n=e.req.query(t);return n===void 0||n===""?[]:n.split(",").filter(Boolean)}async function Cb(e,t){let n=new Map,i=new Map,r=1,o=!0;for(;o;){let a=await BC(e,{...t,cache:n,page:r,page_size:500});for(let s of a.summaries)OQ(s)&&i.set(s.agent_invocation_id,s);o=a.has_more,r+=1}return[...i.values()]}function OQ(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.agent_invocation_id=="string"&&typeof t.root_agent_invocation_id=="string"&&(t.parent_agent_invocation_id===null||typeof t.parent_agent_invocation_id=="string")&&(t.invocation_kind==="orchestrator"||t.invocation_kind==="delegated")&&typeof t.run_id=="string"&&typeof t.quantitative_metrics=="object"&&t.quantitative_metrics!==null&&typeof t.time=="object"&&t.time!==null&&Array.isArray(t.usage_segments)}async function i$(e){try{let t=Di(Nt(await e.readText(".agents/config/agents/catalog.yaml"))).agents;return{agentNames:t.map(n=>n.codex_name),agentNamesById:Object.fromEntries(t.map(n=>[n.id,n.codex_name])),agentNamesByRole:Object.fromEntries(t.map(n=>[n.role,n.codex_name]))}}catch{return{agentNames:[],agentNamesById:{},agentNamesByRole:{}}}}zn();async function al(e){return new Ti(e).readLatestFxRate()}function Ib(e){return["provider","model","agent","phase","status"].every(t=>(e.req.queries(t)?.length??0)===0)}var CQ=".agents/dashboard/work-priority.json";async function as(e,t,n,i=!1,r=!1){let o=await il(e,t,n,{overviewOnly:i,includeOverviewChanges:r}),a=IQ(o,await Xp(e,Yp(o)));if(i||n.from===null||n.to===null)return a;let s=await Cb(e,{from:n.from,to:n.to});return s.length===0?a:Vp({...a,runs:oi(s$(a.runs,s))})}async function Xp(e,t){try{let n=Nb(JSON.parse(await e.readText(CQ)),!1);return t===void 0?n:{...n,item_ids:n.item_ids.filter(i=>t.has(i))}}catch{return{schema_version:1,item_ids:[],updated_at:null}}}function Yp(e){return new Set([...e.prds.map(t=>t.id),...e.specs.map(t=>t.id),...e.tasks.map(t=>t.id)])}function Nb(e,t=!0){let n=typeof e=="object"&&e!==null?e:{};return{schema_version:1,item_ids:Array.isArray(n.item_ids)?[...new Set(n.item_ids.filter(r=>typeof r=="string"&&r.length>0))]:[],updated_at:typeof n.updated_at=="string"&&!t?n.updated_at:new Date().toISOString()}}function IQ(e,t){let n=new Map(t.item_ids.map((r,o)=>[r,o])),i=r=>n.get(r)??null;return{...e,prds:e.prds.map(r=>({...r,manual_order:i(r.id)})),specs:e.specs.map(r=>({...r,manual_order:i(r.id)})),tasks:e.tasks.map(r=>({...r,manual_order:i(r.id)}))}}async function os(e,t,n){let i=new Ti(e),[r,o]=await Promise.all([i.readCatalog(),n==="BRL"?i.readLatestFxRate():Promise.resolve(null)]),a=await i$(e);return W_(t,{catalog:r,fxRate:o,currency:n},a)}async function a$(e,t,n){let i=n.req.query("from")??null,r=n.req.query("to")??null;if(i===null||r===null)return os(e,t,Jn(n));let o={providers:tt(n,"provider"),models:tt(n,"model"),zaip_agents:tt(n,"agent"),phases:tt(n,"phase"),statuses:tt(n,"status")},a=await Cb(e,{from:i,to:r,filters:o});if(a.length===0)return os(e,t,Jn(n));let s=oi(s$(t.runs,a));return os(e,{...t,runs:s},Jn(n))}function s$(e,t){let n=new Set(e.map(i=>i.id));return ol(e,t.filter(i=>n.has(i.run_id)))}async function c$(e,t,n,i,r,o){let a=await PQ(e,i.from,i.to),{from:s,to:l}=a,c={providers:tt(n,"provider"),models:tt(n,"model"),zaip_agents:tt(n,"agent"),phases:tt(n,"phase"),statuses:tt(n,"status")},u=c.providers.length>0||c.models.length>0||c.zaip_agents.length>0||c.statuses.length>0,[d,_]=await Promise.all([Promise.resolve().then(()=>(ea(),KP)).then(({buildQuickOperationsProjection:k})=>k(e,t,{from:s,to:l},{includeBoardTasks:!0})),e.readText(".agents/records/lifecycle/summary.json").then(k=>JSON.parse(k))]),p=r$(_.run_metrics??[],n.req.query("query")??"",d.tasks).filter(k=>$Q(k.finished_at??k.started_at,s,l)).sort((k,P)=>(P.finished_at??P.started_at).localeCompare(k.finished_at??k.started_at)||k.id.localeCompare(P.id)),g=c.phases.length===0?p:p.filter(k=>k.phase!==null&&c.phases.includes(k.phase)),m=await yy(e,{from:s,to:l,filters:c,offset:r,limit:o,...n.req.query("query")?{runIds:new Set(g.map(k=>k.id))}:{}}),f=new Set(m.summaries.map(k=>k.run_id)),v=u?g.filter(k=>f.has(k.id)).map(o$):g.slice(r,r+o).map(o$),S=NQ(v,m.summaries),b=oi(S),h=await os(e,{...d,runs:b},Jn(n));return{...h,page_only:!0,overview:{...h.overview,run_count:0,event_count:0,total_tokens:null,estimated_usd:null,estimated_brl:null,recorded_usd:null,recorded_brl:null,average_run_cost_usd:null,average_run_cost_brl:null,average_run_duration_ms:null,known_tokens_per_cycle:null,top_10_token_share:null},groups:{conversations:[],tasks:[],providers:[],agents:[],models:[],daily:[],monthly:[],annual:[]},run_page:{offset:r,limit:o,total:u?null:g.length,has_more:u?m.has_more:r+o<g.length}}}function NQ(e,t){let n=new Set(e.map(o=>o.id)),i=ol(e,t.filter(o=>n.has(o.run_id))),r=new Map(i.map(o=>[o.id,o]));return e.map(o=>r.get(o.id)??o)}function o$(e){let t={events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},n={...t,events:e.events??0,tokens:{...t.tokens,total:e.total_tokens},cost:{usd:null,brl:e.currency==="BRL"?e.cost:null},coverage:{events:e.events??0,tokens:e.total_tokens===null?0:1,usd:0,brl:e.cost===null?0:1}};return{id:e.id,artifact_path:`.agents/records/runs/${e.id}`,status:e.status==="failed"||e.status==="cancelled"||e.status==="running"?e.status:"completed",phase:e.phase??"execution",entrypoint:e.entrypoint==="observation"?"observation":e.task_id===null?"conversation":"task",work_type:"new",run_role:e.run_kind==="subrun"?"subagent":"orchestrator",run_kind:e.run_kind??"run",run_purpose:e.run_purpose==="observation"?"observation":"execution",requires_finalizer:!1,parent_run_id:e.parent_run_id,client:"unknown",agent:e.agent??"unknown",agent_name:e.agent_name??e.agent??"unknown",provider:e.provider,model:e.model??"unknown",reasoning_effort:null,effective_model:e.model,effective_reasoning_effort:null,effective_config_mixed:!1,call_count:null,terminal_call_count:null,failed_call_count:0,cancelled_call_count:0,conversation_id:e.entrypoint==="observation"?null:e.conversation_id??e.id,execution_id:e.execution_id,task_id:e.task_id,spec_id:e.spec_id,prd_id:e.prd_id,change_id:e.change_id,started_at:e.started_at,finished_at:e.finished_at,duration_ms:e.duration_ms,source_duration_ms:e.duration_ms,usage:{conversation:t,planning:t,execution:n,total:n,new_work:n,rework:t}}}async function PQ(e,t,n){if(t!==null&&n!==null)return{from:t,to:n};let i=await e.readText(".agents/records/lifecycle/summary.json").then(l=>JSON.parse(l)),r=Object.keys(i.periods?.daily??{}).sort(),o=r.at(0),a=r.at(-1),s=new Date().toISOString().slice(0,10);return{from:Kp(t??o??s,"start"),to:Kp(n??a??s,"end")}}function $Q(e,t,n){let i=Date.parse(e),r=Date.parse(Kp(t,"start")),o=Date.parse(Kp(n,"end"));return Number.isFinite(i)&&Number.isFinite(r)&&Number.isFinite(o)&&i>=r&&i<=o}function Kp(e,t){return/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T${t==="start"?"00:00:00.000":"23:59:59.999"}Z`:e}ea();ri();function Qp(e){return e.map(t=>({task_id:t.task_id,duration_ms:t.total_duration_ms,total_tokens:t.total_tokens,total_cost_usd:t.total_cost_usd,cost_brl:t.total_cost_brl,run_count:t.total_run_count}))}var sl=e=>typeof e=="number"&&Number.isFinite(e)?e:null,LQ=(e,t)=>{let n=String(t);return n==="draft"?e==="prd"?"definition":"planning":n==="ready"||n==="planned"?"ready":n==="active"?"executing":n==="delivered"?"completed":["definition","planning","executing","verifying","completed","blocked","failed","cancelled"].includes(n)?n:"planning"};function Pb(e,t){let n=_=>{let p=e.map(g=>g[_]).filter(g=>typeof g=="number"&&Number.isFinite(g));return p.length===0?null:p.reduce((g,m)=>g+m,0)},i=(_,p)=>sl(_[p])??0,r=n("total_duration"),o=n("total_tokens"),a=n("total_cost_usd"),s=n("total_cost_brl"),l={},c={empty:0,structured:0,rework:0};for(let _ of e){let p=LQ(t,_.stage??_.status);l[p]=(l[p]??0)+1;let g=i(_,"rework_run_count")>0?"rework":i(_,"task_count")>0?"structured":"empty";c[g]=(c[g]??0)+1}let u=e.map(_=>({entity_id:String(_.id),title:String(_.title??_.id),duration_ms:sl(_.total_duration),total_tokens:sl(_.total_tokens),total_cost_usd:sl(_.total_cost_usd),cost_brl:sl(_.total_cost_brl),run_count:i(_,"invocation_count")})).toSorted((_,p)=>(p.duration_ms??-1)-(_.duration_ms??-1)||_.entity_id.localeCompare(p.entity_id)).slice(0,5).map(_=>({..._,duration_share:r===null||r===0||_.duration_ms===null?0:_.duration_ms/r})),d=e.flatMap(_=>typeof _.occurred_at=="string"?[_.occurred_at]:[]).toSorted().at(-1)??null;return{status_counts:l,classification_counts:c,entity_count:e.length,total_run_count:e.reduce((_,p)=>_+i(p,"invocation_count"),0),total_duration_ms:r,total_tokens:o,total_cost_usd:a,total_cost_brl:s,average_duration_ms:r===null||e.length===0?null:r/e.length,average_tokens:o===null||e.length===0?null:o/e.length,average_cost_usd:a===null||e.length===0?null:a/e.length,average_cost_brl:s===null||e.length===0?null:s/e.length,latest_created_at:d,top_entities:u}}var u$=require("node:child_process"),d$=require("node:crypto"),$b=require("node:path"),_$=require("node:util");var l$=".agents/dashboard/dashboard.config.json",p$=(0,_$.promisify)(u$.execFile);async function tm(e,t){let n=process.env.ZAIP_DASHBOARD_TITLE?.trim()||"Dashboard ZAIP AIOS",i="auto";try{if(await e.exists(l$)){let r=JSON.parse(await e.readText(l$));typeof r.title=="string"&&r.title.trim()&&(n=r.title.trim()),typeof r.github_repository=="string"&&(i=r.github_repository.trim())}}catch{}if(i.toLowerCase()!=="auto")return{title:n,repository_name:em(i)??""};try{let{stdout:r}=await p$("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",windowsHide:!0});return{title:n,repository_name:em(r)??""}}catch{return{title:n,repository_name:""}}}function em(e){let t=e.trim(),n=t.match(/github\.com(?::|\/)([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i)??t.match(/^([^/:\s]+)\/([^/\s]+?)(?:\.git)?$/);return n?`${n[1]}/${n[2]}`:null}function nm(e){return(0,d$.createHash)("sha256").update(`${(0,$b.resolve)(e)}:dashboard-sqlite`).digest("hex").slice(0,16)}var rm=17e4,ta=class extends Error{constructor(){super(`Open-work reconciliation exceeded ${rm}ms. Canonical records may contain partial changes; the dashboard projection is being refreshed.`),this.name="ReconciliationCommandTimeoutError"}};async function m$(e,t,n={}){let i=x_(t,"reconciliation"),r=n.jobId??i.correlationId;if(i.log("cli_start",{job_id:r,host_terminal_only:n.hostTerminalOnly===!0}),!await e.exists(".agents/runtime/bin/zaip.mjs"))throw i.log("cli_unavailable",{job_id:r}),new Error("ZAIP runtime is unavailable; open work could not be reconciled.");let o=(0,$b.resolve)(t,".agents","runtime","bin","zaip.mjs"),a;try{let s=await p$(process.execPath,[o,"run","reconcile","--open","--json",...n.hostTerminalOnly?["--host-terminal-only"]:[]],{cwd:t,windowsHide:!0,maxBuffer:10485760,timeout:rm,killSignal:"SIGTERM"});a=s.stdout,i.log("cli_output",{job_id:r,stdout:a,stderr:s.stderr})}catch(s){throw i.log("cli_error",{job_id:r,error:s}),typeof s=="object"&&s!==null&&"killed"in s&&s.killed===!0?new ta:s}try{let s=Lb(JSON.parse(a));return i.log("cli_completed",{job_id:r,result:s}),s}catch(s){throw i.log("cli_invalid_result",{job_id:r,error:s,stdout:a}),s}}function Lb(e){let t=new Set,n=new Map,i=new Map,r=new Map,o=(f,v,S)=>{typeof f=="string"&&typeof v=="string"&&r.set(f,{id:f,status:v,reason:typeof S=="string"?S:null})},a=(f,v,S)=>{typeof v=="string"&&f.set(v,typeof S=="string"&&S.trim()?S:null)},s=typeof e=="object"&&e!==null?e:{},l=new Set(["completed","delivered","blocked","cancelled","failed"]),c=Array.isArray(s.reconciliations)?s.reconciliations:[];for(let f of c){if(typeof f!="object"||f===null)continue;let v=f,S=v.error,b=["tasks","changes","executions","specs","prds"].flatMap(h=>Array.isArray(v[h])?v[h]:[]);for(let h of b){if(typeof h!="object"||h===null)continue;let k=h;v.status==="closed"&&l.has(k.status)&&typeof k.id=="string"&&(t.add(k.id),o(k.id,k.status,k.status_reason??S)),k.status==="blocked"?a(n,k.id,k.status_reason??S):v.status==="deferred"&&a(i,k.id,S)}}(Array.isArray(s.runs)?s.runs:[]).forEach(f=>{if(typeof f!="object"||f===null)return;let v=f,S=v.run;typeof S?.run_id=="string"&&(t.add(S.run_id),o(S.run_id,v.status??v.finished?.status,v.finished?.summary))}),(Array.isArray(s.orphaned_executions)?s.orphaned_executions:[]).forEach(f=>{a(n,f,"Execution orphaned after the reconciliation grace period.")}),(Array.isArray(s.orphaned_interaction_executions)?s.orphaned_interaction_executions:[]).forEach(f=>{a(n,f,"Interaction Execution orphaned after the reconciliation grace period.")});for(let f of["orphaned_owner_entities","orphaned_execution_entities"])for(let v of Array.isArray(s[f])?s[f]:[]){if(typeof v!="object"||v===null)continue;let S=v;typeof S.id!="string"||!l.has(S.status)||(t.add(S.id),o(S.id,S.status,S.status_reason),S.status==="blocked"&&a(n,S.id,S.status_reason))}(Array.isArray(s.reconciliation_errors)?s.reconciliation_errors:[]).forEach(f=>{if(typeof f!="object"||f===null)return;let v=f;a(i,v.run_id,v.error)}),(Array.isArray(s.unresolved_running_run_ids)?s.unresolved_running_run_ids:[]).forEach(f=>{a(i,f,"Invocation is still running.")});let m=f=>[...f.entries()].map(([v,S])=>({id:v,reason:S})).sort((v,S)=>v.id.localeCompare(S.id));return{reconciled_ids:[...t].sort(),blocked:m(n),not_reconciled:m(i),outcomes:[...r.values()].sort((f,v)=>f.id.localeCompare(v.id))}}function ss(e){return e.status==="completed"?"completed":e.status==="cancelled"?"cancelled":e.status==="failed"?"failed":e.status==="blocked"?"blocked":e.is_active===!0||e.status==="executing"?"executing":e.status==="verifying"?"verifying":(e.attempt_count??0)>0||e.started_at!=null||e.execution_started===!0?"executing":e.status==="draft"?null:e.status==="planned"?"ready":null}function im(e,t){if(e.lifecycle_status==="cancelled")return"cancelled";if(e.lifecycle_status==="failed")return"failed";if(e.lifecycle_status==="blocked")return"blocked";if(e.lifecycle_status==="delivered"||e.lifecycle_status==="completed")return"completed";if(e.lifecycle_status==="ready")return"ready";if(e.kind==="prd"&&e.lifecycle_status==="draft")return"definition";if(e.kind==="spec"&&e.lifecycle_status==="draft")return"planning";if(e.work_status==="cancelled")return"cancelled";if(e.work_status==="failed")return"failed";if(e.work_status==="blocked")return"blocked";if(e.work_status==="completed")return"completed";if(e.is_active||t.some(n=>e.task_ids.includes(n.id)&&n.is_active))return"executing";if(e.lifecycle_status==="verifying"||e.work_status==="verifying")return"verifying";if(e.work_status==="executing"){let n=t.filter(i=>e.task_ids.includes(i.id));return n.length>0&&n.every(i=>i.status==="verifying"||i.status==="completed")?"verifying":"executing"}return e.lifecycle_status==="active"?"executing":"planning"}qe();function om(e){return/^\.agents\/(?:data|records)\/(?:executions\/.*\/execution\.md|changes\/.*\/change\.md|(?:changes|executions)\/.*\/decisions\/.*\.md)$/.test(e)}function Mb(e){let t=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(e)?.[1];if(t===void 0)return null;try{let n=Nt(t);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function cs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function pt(e){return typeof e=="string"&&e.length>0?e:null}function cl(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Sn(e){let t=[...new Set(e.filter(n=>typeof n=="string"&&n.length>0&&n!=="unavailable"))];return t.length===0?null:t.length===1?t[0]:"mixed"}zn();var MQ=new Intl.DateTimeFormat("en",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"});function bt(e){let t=Object.fromEntries(MQ.formatToParts(new Date(e)).filter(n=>n.type!=="literal").map(n=>[n.type,n.value]));return`${t.year}-${t.month}-${t.day}`}var b$=require("node:fs"),Db=require("node:path"),jb=require("node:sqlite");var h$=require("node:crypto"),DQ=require("node:sqlite"),am=[["first_fold_viewport_cache","first_fold_viewport_cache:all_time"],["first_fold_all_time_cache","first_fold_all_time_cache:all_time"],["first_fold_all_time_board_cache","first_fold_all_time_board_cache:all_time"],["cost_monitor_summary_cache","cost_monitor_summary_cache:all_time"],["cost_monitor_summary_month_cache","cost_monitor_summary_month_cache:current"],["first_fold_monthly_quick_cache","first_fold_monthly_quick_cache:default"]];function f$(e,t){let n=e.prepare("SELECT payload_json FROM zaip_aios_activities WHERE payload_type=? ORDER BY recorded_at DESC LIMIT 1").get(t);if(typeof n?.payload_json!="string")return null;try{let i=JSON.parse(n.payload_json);return i!==null&&typeof i=="object"?i:null}catch{return null}}function jQ(e,t,n){let i="json_extract(payload_json, '$.occurred_day_sp')",r=t&&n?` AND ${i} >= ? AND ${i} <= ?`:"",o=e.prepare(`SELECT json_extract(payload_json, '$.entity_kind') AS kind, COUNT(*) AS count
|
|
364
|
-
FROM zaip_aios_activities WHERE payload_type='work_item'${r} GROUP BY kind`).all(...t&&n?[t,n]:[]);return Object.fromEntries(o.map(a=>[a.kind,Number(a.count)]))}function g$(e,t,n=!1){let i=typeof t.from_day=="string"?t.from_day:void 0,r=typeof t.to_day=="string"?t.to_day:void 0;if(n&&(!i||!r))return!1;let o=
|
|
363
|
+
`)}finally{c!==void 0&&clearTimeout(c),o(s)}})})}function D_(e,t){let n=e.length;return{tasks:M_(e.map(i=>i.task_count),n),specs:M_(e.map(i=>i.spec_count),n),prds:M_(e.map(i=>i.prd_count),n),durationMs:M_(e.map(i=>i.duration_ms),n),tokens:mC(e.map(i=>i.total_tokens)),cost:mC(e.map(i=>t==="BRL"?i.estimated_brl:i.estimated_usd))}}function mC(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function M_(e,t){return t===0||e.every(n=>n===null)?null:e.reduce((n,i)=>n+(i??0),0)/t}zn();Ma();function GC(e,t){let n=new Map(e.map(i=>[i.key,i]));for(let i of t??[])n.has(i)||n.set(i,u9(i));return[...n.values()].sort((i,r)=>r.latest_started_at.localeCompare(i.latest_started_at)||i.label.localeCompare(r.label))}function u9(e){return{key:e,label:e,latest_started_at:"",run_count:0,task_count:0,prd_count:0,spec_count:0,evidence_count:0,test_count:0,event_count:0,total_tokens:0,estimated_usd:0,estimated_brl:0,duration_ms:0,duration:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},coverage:{events:0,tokens:0,usd:0,brl:0}}}function by(e){return e.length===0||e.some(t=>t===null)?null:e.reduce((t,n)=>t+(n??0),0)/e.length}function Da(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function kc(e,t="all_invocations"){let n=new Map;for(let a of e)n.has(a.run_id)||n.set(a.run_id,a);let i=[...n.values()];if(t==="all_invocations")return i;let r=new Set(i.map(a=>a.run_id));return t==="all_execution"?i.filter(a=>a.phase==="execution"):i.filter(a=>a.phase==="execution"&&(a.parent_run_id===null||!r.has(a.parent_run_id)))}function q_(e,t="all_invocations"){let n=kc(e,t),i=n.filter(o=>o.duration_ms!==null),r=n.length-i.length;return{known_sum:i.reduce((o,a)=>o+a.duration_ms,0),unknown:r,complete:r===0,coverage_ratio:n.length===0?1:i.length/n.length}}function V_(e){let t=e?.trim().toLowerCase();return!t||t==="unknown"||t==="codex"?"openai":t}var d9={events:0,tokens:0,usd:0,brl:0};function XC(e,t){let n=new Map;for(let l of t)l.task_id!==null&&n.set(l.task_id,[...n.get(l.task_id)??[],l]);let i=e.filter(l=>n.has(l.id)).map(l=>YC(l,n.get(l.id)??[])),r=new Set(e.map(l=>l.id)),o=[...n].filter(([l])=>!r.has(l)).map(([l,c])=>KC(l,c)),a=t.filter(l=>l.task_id===null),s=a.length===0?[]:[KC("Sem tarefa vinculada",a)];return[...i,...o,...s].sort((l,c)=>c.latest_started_at.localeCompare(l.latest_started_at))}function KC(e,t){return{...YC({id:e,title:e,created_at:t[0]?.started_at??"",test_count:0},t),label:`Tarefa hist\xF3rica: ${e}`,latest_started_at:t.reduce((n,i)=>i.started_at>n?i.started_at:n,"")}}function YC(e,t){let n=q_(t);return{key:e.id,label:e.title,latest_started_at:e.created_at,run_count:t.length,task_count:1,tasksCreated:1,tasksActive:1,prd_count:0,spec_count:0,evidence_count:0,test_count:e.test_count??0,event_count:t.reduce((i,r)=>i+(r.event_count??0),0),total_tokens:Da(t.map(i=>i.total_tokens)),estimated_usd:Da(t.map(i=>i.estimated_usd)),estimated_brl:Da(t.map(i=>i.estimated_brl)),duration_ms:n.known_sum,duration:n,coverage:t.reduce((i,r)=>({events:i.events+r.coverage.events,tokens:i.tokens+r.coverage.tokens,usd:i.usd+r.coverage.usd,brl:i.brl+r.coverage.brl}),d9),coverage_counts:{source:"run_rows",granularity:"event",events:t.reduce((i,r)=>i+r.coverage.events,0),tokens:null,usd:null,brl:null,metrics:{tokens:Sy(t,i=>i.total_tokens),usd:Sy(t,i=>i.estimated_usd),brl:Sy(t,i=>i.estimated_brl)}}}}function Sy(e,t){let n=e.filter(i=>t(i)!==null).length;return{eligible_runs:e.length,known_runs:n,unknown_runs:e.length-n}}function ja(e,t,n=r=>r,i="all_invocations"){let r=[...new Set(e.map(t).filter(a=>a!==null))],o=new Set(kc(e,i).map(a=>a.run_id));return r.map(a=>{let s=e.filter(c=>t(c)===a),l=q_(s.filter(c=>o.has(c.run_id)),i);return{key:a,label:n(a),latest_started_at:s.reduce((c,u)=>u.started_at>c?u.started_at:c,s[0]?.started_at??""),run_count:s.length,task_count:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,tasksActive:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,taskDaysActive:new Set(s.flatMap(c=>c.task_id===null?[]:[c.task_id])).size,prd_count:0,spec_count:0,evidence_count:0,test_count:0,event_count:s.reduce((c,u)=>c+(u.event_count??0),0),total_tokens:ky(s.map(c=>c.total_tokens)),estimated_usd:ky(s.map(c=>c.estimated_usd)),estimated_brl:ky(s.map(c=>c.estimated_brl)),duration_ms:l.known_sum,duration:l,coverage:_9(s)}}).sort(p9)}function ky(e){return Da(e)}function QC(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)/t.length}function _9(e){return e.reduce((t,n)=>({events:t.events+n.coverage.events,tokens:t.tokens+n.coverage.tokens,usd:t.usd+n.coverage.usd,brl:t.brl+n.coverage.brl}),{events:0,tokens:0,usd:0,brl:0})}function p9(e,t){return t.latest_started_at.localeCompare(e.latest_started_at)}function W_(e,t,n){if(e.schema_version!==2)throw new TypeError("Cost Monitor accepts only OperationsProjection V2");let i=t?.currency??"BRL",r=ni(n?.agentNames??[]),o=e.runs,a=new Map(e.runs.map(h=>[h.id,h])),s=o,l=s,c=new Map(e.tasks.map(h=>[h.id,h])),d=l.map(h=>{let k=h.task_id===null?void 0:c.get(h.task_id),P=a.get(h.id),U=P?.usage.total.cost??{usd:null,brl:null},$=(P?.pricing_segments??[]).map(Q=>Q.recorded_fx_rate??nI(Q.recorded_usd??null,Q.recorded_brl??null)).filter(Q=>Q!==null),B=h.usage.total,z=B.coverage.tokens>0,R=B.coverage.usd>0,L=B.coverage.brl>0,J=t?g9(h,t):null,le=z?oI(P?.usage.total.tokens??B.tokens):null,j=k9(h);return{run_id:h.id,execution_id:h.execution_id,conversation_id:h.conversation_id,task_id:h.task_id,task_title:k?.title??h.task_id??h.conversation_id??h.id,task_status:k?.status??h.status,priority:k?.priority??"none",risk:k?.risk??"none",spec_id:h.spec_id,prd_id:h.prd_id,change_id:h.change_id,parent_run_id:h.parent_run_id,run_role:h.run_role,run_kind:h.run_kind,run_purpose:h.run_purpose,requires_finalizer:h.requires_finalizer,client:h.client,agent:h.agent,agent_name:f9(h,n),provider:V_(h.provider),model:h.effective_model??h.model,requested_model:h.model,reasoning_effort:h.reasoning_effort??null,effective_reasoning_effort:h.effective_reasoning_effort,service_tier:h.service_tier??null,call_count:h.call_count,status:h.status,phase:m9(h),origin:h.entrypoint,work_type:h.work_type,started_at:h.started_at,finished_at:h.finished_at,...j,estimation_basis:null,source_started_at:h.source_started_at??null,source_finished_at:h.source_finished_at??null,capture_lag_ms:h.capture_lag_ms??null,event_count:B.events,input_tokens:B.tokens.input,cached_input_tokens:B.tokens.cached_input,output_tokens:B.tokens.output,reasoning_tokens:B.tokens.reasoning,total_tokens:le,uncached_input_tokens:B.tokens.input===null?null:Math.max(B.tokens.input-(B.tokens.cached_input??0),0),visible_output_tokens:B.tokens.output===null?null:Math.max(B.tokens.output-(B.tokens.reasoning??0),0),input_rate_usd_per_million:J?.rates.input??null,cached_input_rate_usd_per_million:J?.rates.cached??null,output_rate_usd_per_million:J?.rates.output??null,reasoning_rate_usd_per_million:J?.rates.reasoning??null,context_input_multiplier:J?.context.input??null,context_output_multiplier:J?.context.output??null,speed_cost_multiplier:J?.speedMultiplier??null,standard_cost_usd:J?.standardUsd??null,speed_uplift_usd:J?.upliftUsd??null,input_cost_usd:J?.components.input??null,cached_input_cost_usd:J?.components.cached??null,output_cost_usd:J?.components.output??null,reasoning_cost_usd:J?.components.reasoning??null,fx_rate:i==="BRL"?t?.fxRate?.rate??null:null,estimated_usd:R?U.usd:null,estimated_brl:L?U.brl:null,recorded_usd:R?U.usd:null,recorded_brl:L?U.brl:null,recorded_fx_rate:S9($)??nI(U.usd,U.brl),coverage:B.coverage,artifact_path:h.artifact_path}}),_=(h,k,P)=>ja(d,h,k,P),p=eo(s),g={conversation:eo(s.filter(h=>h.entrypoint==="conversation")),task:eo(s.filter(h=>h.entrypoint==="task")),spec:eo(s.filter(h=>h.entrypoint==="spec")),prd:eo(s.filter(h=>h.entrypoint==="prd"))},m=p.total,f=d.filter(h=>h.total_tokens!==null),v=f.reduce((h,k)=>h+(k.total_tokens??0),0),S=f.reduce((h,k)=>h+(k.event_count??0),0),b=[...f].sort((h,k)=>(k.total_tokens??0)-(h.total_tokens??0)).slice(0,10).reduce((h,k)=>h+(k.total_tokens??0),0);return{schema_version:2,layout_version:2,readonly:!0,legacy_effort_baseline:{cutoff:gn.cutoff,duration_ms:gn.durationMs},source:e.source,currency:i,pricing:{catalog_updated_at:t?.catalog.updated_at??null,fx_rate:i==="BRL"?t?.fxRate?.rate??null:null,conversion_applied:t!==void 0&&i==="BRL"&&t.fxRate!==null},filters:e.filters,overview:{task_count:new Set(d.flatMap(h=>h.task_id===null?[]:[h.task_id])).size,run_count:d.length,event_count:d.reduce((h,k)=>h+(k.event_count??0),0),total_tokens:m.tokens.total,estimated_usd:m.cost.usd,estimated_brl:m.cost.brl,recorded_usd:tI(s.map(h=>a.get(h.id)?.usage.total.cost.usd??null)),recorded_brl:tI(s.map(h=>a.get(h.id)?.usage.total.cost.brl??null)),average_run_cost_usd:by(d.map(h=>h.estimated_usd)),average_run_cost_brl:by(d.map(h=>h.estimated_brl)),average_run_duration_ms:QC(kc(d).map(h=>h.duration_ms)),known_tokens_per_cycle:S===0?null:v/S,top_10_token_share:v===0?null:b/v,coverage:m.coverage},filters_available:{providers:ni(d.map(h=>V_(h.provider))),agents:ni(d.map(h=>h.agent_name)),models:ni(d.map(h=>h.model)),statuses:ni(d.map(h=>h.task_status)),priorities:ni(d.map(h=>h.priority)),risks:ni(d.map(h=>h.risk)),phases:ni(d.map(h=>h.phase)),origins:ni(d.map(h=>h.origin)),work_types:ni(d.map(h=>h.work_type))},configured_agents:r,usage:p,origins:g,prds:rI(e.prds,s),specs:rI(e.specs,s),runs:[...d].sort((h,k)=>k.started_at.localeCompare(h.started_at)),groups:{conversations:ja(d,h=>h.conversation_id,void 0,"all_invocations"),tasks:XC(e.tasks,d),providers:_(h=>V_(h.provider)),agents:GC(_(h=>h.agent_name),r),models:_(h=>h.model),daily:wy(ja(d,h=>{let k=h.finished_at??h.started_at;return Wt(k,"day")??k.slice(0,10)},void 0,"all_invocations"),e.tasks,"day"),monthly:wy(ja(d,h=>{let k=h.finished_at??h.started_at;return Wt(k,"month")??k.slice(0,7)},void 0,"all_invocations"),e.tasks,"month"),annual:wy(ja(d,h=>{let k=h.finished_at??h.started_at;return Wt(k,"year")??k.slice(0,4)},void 0,"all_invocations"),e.tasks,"year")}}}function wy(e,t,n){let i=new Map(e.map(r=>[r.key,{...r,tasksActive:r.tasksActive??r.task_count,taskDaysActive:r.tasksActive??r.task_count,tasksCreated:0}]));for(let r of t){let o=Wt(r.created_at,n);if(o===null)continue;let a=i.get(o);a!==void 0&&(a.tasksCreated=(a.tasksCreated??0)+1)}return[...i.values()]}function m9(e){return e.entrypoint==="task"&&e.phase==="conversation"?"planning":e.phase}function f9(e,t){if(e.agent==="codex")return"codex";let n=t?.agentNamesById?.[e.agent];if(n!==void 0)return n;if(e.agent==="agent-orchestrator")return t?.agentNamesByRole?.orchestrator??"zaip-agent-orchestrator";if(e.agent_name.trim()===e.agent){let i=t?.agentNamesByRole?.[e.run_role];if(i!==void 0)return i}return e.agent_name!=="codex",e.agent_name}function g9(e,t){let n=e.pricing_segments??[],i=n.length>0?n.map(m=>({provider:m.provider,model:m.model??e.effective_model??e.model,serviceTier:m.service_tier??e.service_tier??"default",usage:v9(m)})):[{provider:e.provider,model:e.effective_model??e.model,serviceTier:e.service_tier??"default",usage:b9(e.usage.total)}],r=i.map(m=>Mo({provider:m.provider==="openai"||m.provider==="anthropic"?m.provider:null,model:m.model,serviceTier:m.serviceTier,usage:m.usage,catalog:t.catalog,fxRate:null})),o=i.map(m=>Mo({provider:m.provider==="openai"||m.provider==="anthropic"?m.provider:null,model:m.model,serviceTier:"default",usage:m.usage,catalog:t.catalog,fxRate:null})),a=eI(r.map(m=>m.estimated_usd)),s=eI(o.map(m=>m.estimated_usd)),l=a,c=l===null&&s!==null,u=h9(i,t.catalog),d=y9(t.catalog,i.map(m=>m.model)),_=i.some(m=>m.serviceTier==="priority"||m.serviceTier==="fast"),p=(m,f)=>_&&!c?f:m,g=i.some(m=>d?.long_context_threshold_tokens!==null&&d?.long_context_threshold_tokens!==void 0&&(m.usage.input??0)>d.long_context_threshold_tokens);return{rates:{input:d?p(d.input_per_million_usd,d.priority_input_per_million_usd??null):null,cached:d?p(d.cached_input_per_million_usd,d.priority_cached_input_per_million_usd??null):null,output:d?p(d.output_per_million_usd,d.priority_output_per_million_usd??null):null,reasoning:d?p(d.reasoning_per_million_usd??d.output_per_million_usd,d.priority_reasoning_per_million_usd??d.priority_output_per_million_usd??null):null},context:{input:d?g?d.long_context_input_multiplier:1:null,output:d?g?d.long_context_output_multiplier:1:null},speedMultiplier:l!==null&&s!==null&&s>0?Math.round(l/s*1e3)/1e3:null,standardUsd:s,upliftUsd:l!==null&&s!==null?B_(l-s):null,components:{input:u?.input??null,cached:u?.cached??null,output:u?.output??null,reasoning:u?.reasoning??null}}}function h9(e,t){let n=0,i=0,r=0;for(let o of e){let a=iI(t,o.model);if(a===null||o.provider!==null&&o.provider!==a.provider||o.usage.input===null||o.usage.cached_input===null||o.usage.output===null)return null;let s=a.long_context_threshold_tokens!==null&&o.usage.input>a.long_context_threshold_tokens,l=o.serviceTier==="priority"||o.serviceTier==="fast",c=a.priority_input_per_million_usd,u=a.priority_output_per_million_usd,d=l&&!s&&c!==null&&c!==void 0&&u!==null&&u!==void 0,_=d&&c!==null&&c!==void 0?c:a.input_per_million_usd,p=d?a.priority_cached_input_per_million_usd??0:a.cached_input_per_million_usd??0,g=d&&u!==null&&u!==void 0?u:a.output_per_million_usd,m=s?a.long_context_input_multiplier:1,f=s?a.long_context_output_multiplier:1,v=Math.max(o.usage.input-o.usage.cached_input,0);n+=v/1e6*_*m,i+=o.usage.cached_input/1e6*p*m,r+=o.usage.output/1e6*g*f}return{input:n,cached:i,output:r,reasoning:0}}function iI(e,t){let n=t.toLowerCase();return e.models.find(i=>i.id.toLowerCase()===n||i.aliases.some(r=>r.toLowerCase()===n))??null}function y9(e,t){let n=t.map(r=>iI(e,r));if(n.some(r=>r===null))return null;let i=n[0];return!i||n.some(r=>r?.id!==i.id)?null:i}function v9(e){return{input:e.input_tokens,cached_input:e.cached_input_tokens,output:e.output_tokens,reasoning:e.reasoning_tokens,total:e.total_tokens,source:"provider_reported"}}function b9(e){return{input:e.tokens.input,cached_input:e.tokens.cached_input,output:e.tokens.output,reasoning:e.tokens.reasoning,total:e.tokens.total,source:"provider_reported"}}function eI(e){return e.length===0||e.some(t=>t===null)?null:B_(e.reduce((t,n)=>t+n,0))}function tI(e){let t=e.filter(n=>n!==null);return t.length===0?null:B_(t.reduce((n,i)=>n+i,0))}function B_(e){return Math.round(e*1e6)/1e6}function nI(e,t){return e!==null&&e>0&&t!==null?B_(t/e):null}function S9(e){if(e.length===0)return null;let t=e[0]??null;return e.every(n=>n===t)?t:null}function k9(e){return typeof e.source_duration_ms=="number"&&e.source_duration_ms>=0?{duration_ms:e.source_duration_ms,duration_provenance:"observed"}:typeof e.duration_ms=="number"&&e.duration_ms>=0&&(e.duration_provenance===void 0||e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")?{duration_ms:e.duration_ms,duration_provenance:e.duration_provenance??"legacy_inferred"}:{duration_ms:null,duration_provenance:"unavailable"}}function eo(e){return Object.fromEntries(["conversation","planning","execution","total","new_work","rework"].map(n=>[n,w9(e.map(i=>i.usage[n]))]))}function w9(e){let t=n=>{let i=n.filter(r=>r!==null);return i.length===0?null:i.reduce((r,o)=>r+o,0)};return{events:e.reduce((n,i)=>n+i.events,0),duration_ms:t(e.map(n=>n.duration_ms??null)),tokens:{input:t(e.map(n=>n.tokens.input)),cached_input:t(e.map(n=>n.tokens.cached_input)),output:t(e.map(n=>n.tokens.output)),reasoning:t(e.map(n=>n.tokens.reasoning)),total:t(e.map(n=>oI(n.tokens)))},cost:{usd:t(e.map(n=>n.cost.usd)),brl:t(e.map(n=>n.cost.brl))},coverage:{events:e.reduce((n,i)=>n+i.coverage.events,0),tokens:e.reduce((n,i)=>n+i.coverage.tokens,0),usd:e.reduce((n,i)=>n+i.coverage.usd,0),brl:e.reduce((n,i)=>n+i.coverage.brl,0)}}}function oI(e){return e.input!==null&&e.output!==null?e.input+e.output:e.total}function rI(e,t){return e.map(n=>{let i=new Set(n.run_ids),r=t.filter(o=>i.has(o.id)||n.kind==="prd"&&o.prd_id===n.id||n.kind==="spec"&&o.spec_id===n.id);return{...n,usage:eo(r)}})}function ni(e){return[...new Set(e)].sort()}Ma();ea();function is(){return{events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}}}function XP(){let e=()=>({conversation:is(),planning:is(),execution:is(),total:is(),new_work:is(),rework:is()});return{conversation:e(),task:e(),spec:e(),prd:e()}}function Gp(e,t,n,i){let r=(e.run_metrics??[]).map(b8),o=r.filter(z=>{let R=Wt(z.finished_at??z.started_at,"day");return R!==null&&QP(R,t.filters.from,t.filters.to)}).map(v8),a=t.schema_version===2?W_({...t,tasks:t.tasks??[],runs:o},void 0):null,s=z=>z.filter(R=>{let L=R.key.trim().toLowerCase();return L.length>0&&!["mixed","unknown","unavailable"].includes(L)}),l=e.run_metrics!==void 0,c=e.cost_monitor_daily_duration!==void 0||e.canonical_daily_duration_ms!==void 0,u=new Map(Object.entries(S8(e)));for(let z of Object.keys(e.cost_monitor_daily_duration??{}))u.has(z)||u.set(z,xb());if(!l&&!c)for(let z of Object.keys(ti))u.has(z)||u.set(z,xb());let d=[...u].filter(([z])=>QP(z,t.filters.from,t.filters.to)),_=w8(r),p=e.cost_monitor_daily_duration,g=(z,R)=>{if(p!==void 0){let L=p[z];return L===void 0?Eb():{value:{known_sum:L.known_sum,unknown:L.eligible_runs-L.known_runs,complete:L.eligible_runs===L.known_runs,coverage_ratio:L.eligible_runs===0?1:L.known_runs/L.eligible_runs},population:ai(L.eligible_runs,L.known_runs)}}if(e.canonical_daily_duration_ms!==void 0){let L=e.canonical_daily_duration_ms[z];return L===void 0?Eb():{value:{known_sum:L,unknown:0,complete:!0,coverage_ratio:1},population:ai(R.runs,R.runs)}}return l?_.get(z)??Eb():y8(z,R)},m=new Map((e.daily_rows??[]).map(z=>[z.key,z])),v=d.map(([z,R])=>k8(z,R,i,g(z,R),m.get(z))),S=v.reduce((z,R)=>z+R.run_count,0),b=v.reduce((z,R)=>z+R.event_count,0),h=!c&&o.every(z=>z.usage.total.tokens.total===null)?null:Ab(v.map(z=>z.total_tokens)),k=!c&&o.every(z=>z.usage.total.cost.brl===null)?null:Ab(v.map(z=>z.estimated_brl)),P=Ab(v.map(z=>z.estimated_usd)),U=E8(e.run_metrics??[]),$=t.summary.overview_metrics?.task_count??t.summary.task_count,B={events:S,tokens:v.reduce((z,R)=>z+R.coverage.tokens,0),usd:v.reduce((z,R)=>z+R.coverage.usd,0),brl:v.reduce((z,R)=>z+R.coverage.brl,0)};return{schema_version:2,layout_version:t.layout_version,readonly:!0,source:".agents/records",aggregate_only:!0,data_source:l||c?"run_records":"lifecycle_manifest_summary",legacy_effort_baseline:!l&&!c&&t.filters.from===null&&t.filters.to===null?{cutoff:gn.cutoff,duration_ms:gn.durationMs}:null,currency:n,pricing:{catalog_updated_at:null,fx_rate:i,conversion_applied:i!==null},filters:t.filters,overview:{task_count:$,run_count:S,event_count:b,total_tokens:h,estimated_usd:P,estimated_brl:k,recorded_usd:null,recorded_brl:null,average_run_cost_usd:S===0||P===null||B.usd!==S?null:P/S,average_run_cost_brl:S===0||k===null||B.brl!==S?null:k/S,average_run_duration_ms:U,known_tokens_per_cycle:S===0||h===null?null:h/S,top_10_token_share:null,coverage:B},filters_available:{providers:e.filters_available?.providers??a?.filters_available.providers??[],agents:e.filters_available?.agents??a?.filters_available.agents??[],models:e.filters_available?.models??a?.filters_available.models??[],statuses:e.filters_available?.statuses??a?.filters_available.statuses??[],priorities:e.filters_available?.priorities??a?.filters_available.priorities??[],risks:e.filters_available?.risks??a?.filters_available.risks??[],phases:e.filters_available?.phases??a?.filters_available.phases??[],origins:e.filters_available?.origins??a?.filters_available.origins??[],work_types:e.filters_available?.work_types??a?.filters_available.work_types??[]},configured_agents:a?.configured_agents??[],usage:e.aggregate_usage??a?.usage??eo(o),origins:XP(),prds:a?.prds??t.prds,specs:a?.specs??t.specs,runs:[],groups:{conversations:[],tasks:[],providers:s(a?.groups.providers??[]),agents:a?.groups.agents??[],models:s(e.model_groups??a?.groups.models??[]),daily:v,monthly:YP(v,7),annual:YP(v,4)}}}function y8(e,t){if((ti[e]??0)>0)return Yo(e,t);if(t.duration!==void 0){let n=Rb(t.runs,t.duration.unknown);return{value:t.duration,population:ai(t.runs,n)}}return{value:{known_sum:0,unknown:t.runs,complete:t.runs===0,coverage_ratio:t.runs===0?1:0},population:ai(t.runs,0)}}function xb(){let e={known_sum:0,unknown:0,complete:!0,coverage_ratio:1};return{prds:0,specs:0,tasks:0,validations:0,evidences:0,runs:0,usage:{total_tokens:e,cost:{...e,currency:"BRL"}}}}function v8(e){let t={events:0,duration_ms:null,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},n={...t,events:e.events??0,duration_ms:e.source_duration_ms??null,tokens:{...t.tokens,input:e.input_tokens??null,cached_input:e.cached_input_tokens??null,output:e.output_tokens??null,reasoning:e.reasoning_tokens??null,total:e.total_tokens},cost:{usd:null,brl:e.currency==="BRL"?e.cost:null},coverage:{events:e.events??0,tokens:e.total_tokens===null?0:1,usd:0,brl:e.cost===null?0:1}},i=e.phase==="conversation"||e.phase==="planning"?e.phase:"execution";return{id:e.id,artifact_path:`.agents/records/runs/${e.id}`,status:e.status==="failed"||e.status==="cancelled"||e.status==="running"?e.status:"completed",phase:i,entrypoint:e.entrypoint==="observation"?"observation":e.task_id===null?"conversation":"task",work_type:"new",run_role:e.run_kind==="subrun"?"subagent":"orchestrator",run_kind:e.run_kind??"run",run_purpose:e.run_purpose==="observation"?"observation":"execution",requires_finalizer:!1,parent_run_id:e.parent_run_id,client:"unknown",agent:e.agent??"unknown",agent_name:e.agent_name??e.agent??"unknown",provider:e.provider??"unavailable",model:e.model??"unknown",reasoning_effort:null,effective_model:e.model??null,effective_reasoning_effort:null,effective_config_mixed:!1,call_count:null,terminal_call_count:null,failed_call_count:0,cancelled_call_count:0,conversation_id:e.entrypoint==="observation"?null:e.conversation_id??e.id,execution_id:e.execution_id??null,task_id:e.task_id,spec_id:e.spec_id??null,prd_id:e.prd_id??null,change_id:e.change_id??null,started_at:e.started_at,finished_at:e.finished_at,duration_ms:e.duration_ms,source_duration_ms:e.source_duration_ms??null,...e.duration_provenance===void 0?{}:{duration_provenance:e.duration_provenance},...e.estimation_basis===void 0?{}:{estimation_basis:e.estimation_basis},usage:{conversation:i==="conversation"?n:t,planning:i==="planning"?n:t,execution:i==="execution"?n:t,total:n,new_work:n,rework:t}}}function b8(e){let t=e.source_duration_ms??e.duration_ms,n=e.source_duration_ms!==null&&e.source_duration_ms!==void 0?"observed":e.duration_provenance??"legacy_inferred";return typeof t=="number"&&t>=0&&(n==="observed"||n==="reconciled"||n==="legacy_inferred")?{...e,duration_ms:t,duration_provenance:n,estimation_basis:null}:{...e,duration_ms:null,duration_provenance:"unavailable",estimation_basis:null}}function S8(e){let t=[...new Map((e.run_metrics??[]).map(r=>[r.id,r])).values()];if(e.run_metrics===void 0)return e.periods.daily;let n=new Map;for(let r of t){let o=Wt(r.started_at,"day");o!==null&&n.set(o,[...n.get(o)??[],r])}let i=new Set([...Object.keys(e.periods.daily),...n.keys()]);return Object.fromEntries([...i].map(r=>{let o=e.periods.daily[r]??xb(),a=n.get(r)??[],s=kb(a.map(u=>u.total_tokens)),l=kb(a.map(u=>u.cost)),c=kb(a.map(u=>u.events));return[r,{...o,runs:a.length,usage:{total_tokens:s,cost:{...l,currency:a.find(u=>u.currency!==null)?.currency??o.usage.cost.currency}},events:c}]}))}function kb(e){let t=e.filter(i=>i!==null),n=e.length-t.length;return{known_sum:t.reduce((i,r)=>i+r,0),unknown:n,complete:n===0,coverage_ratio:e.length===0?1:t.length/e.length}}function k8(e,t,n,i,r){let o=t.usage.cost.known_sum===0&&t.usage.cost.unknown>0?null:t.usage.cost.known_sum,a=r===void 0?o:r.total_cost_brl,s=r===void 0?a!==null&&n!==null&&n>0?a/n:null:r.total_cost_usd,l=t.events?.known_sum??0,c=Rb(t.runs,t.usage.total_tokens.unknown),u=Rb(t.runs,t.usage.cost.unknown);return{key:e,label:e,latest_started_at:`${e}T23:59:59.999-03:00`,run_count:t.runs,task_count:t.tasks,tasksCreated:t.tasks,tasksActive:t.tasks,taskDaysActive:t.tasks,prd_count:t.prds,spec_count:t.specs,evidence_count:t.evidences,test_count:t.validations,event_count:l,total_tokens:t.usage.total_tokens.known_sum===0&&t.usage.total_tokens.unknown>0?null:t.usage.total_tokens.known_sum,estimated_usd:s,estimated_brl:a,duration_ms:i.population.known_runs>0?i.value.known_sum:null,duration:i.value,coverage:{events:t.runs,tokens:c,usd:u,brl:u},coverage_counts:{source:"period_summary",granularity:t.events===void 0?"unavailable":"event",events:t.events?.known_sum??null,tokens:null,usd:null,brl:null,metrics:{duration:i.population,tokens:ai(t.runs,c),usd:ai(t.runs,u),brl:ai(t.runs,u)}}}}function YP(e,t){let n=new Map;for(let i of e){let r=i.key.slice(0,t);n.set(r,[...n.get(r)??[],i])}return[...n].map(([i,r])=>{let o=r[0],a=r.reduce((d,_)=>d+_.duration.known_sum,0),s=r.reduce((d,_)=>d+_.duration.unknown,0),l=r.reduce((d,_)=>d+(_.coverage_counts?.metrics?.duration?.eligible_runs??0),0),c=r.reduce((d,_)=>d+(_.coverage_counts?.metrics?.duration?.known_runs??0),0),u=r.reduce((d,_)=>d+_.run_count,0);return{...o,key:i,label:i,latest_started_at:r.map(d=>d.latest_started_at).sort().at(-1)??o.latest_started_at,run_count:u,task_count:r.reduce((d,_)=>d+(_.task_count??0),0),tasksCreated:r.reduce((d,_)=>d+(_.tasksCreated??0),0),tasksActive:r.reduce((d,_)=>d+(_.tasksActive??0),0),taskDaysActive:r.reduce((d,_)=>d+(_.taskDaysActive??0),0),prd_count:r.reduce((d,_)=>d+(_.prd_count??0),0),spec_count:r.reduce((d,_)=>d+(_.spec_count??0),0),evidence_count:r.reduce((d,_)=>d+(_.evidence_count??0),0),test_count:r.reduce((d,_)=>d+(_.test_count??0),0),event_count:r.reduce((d,_)=>d+_.event_count,0),total_tokens:Tb(r.map(d=>d.total_tokens)),estimated_usd:Tb(r.map(d=>d.estimated_usd)),estimated_brl:Tb(r.map(d=>d.estimated_brl)),duration_ms:s===0?a:null,duration:{known_sum:a,unknown:s,complete:s===0,coverage_ratio:l===0?1:c/l},coverage:{events:r.reduce((d,_)=>d+_.coverage.events,0),tokens:r.reduce((d,_)=>d+_.coverage.tokens,0),usd:r.reduce((d,_)=>d+_.coverage.usd,0),brl:r.reduce((d,_)=>d+_.coverage.brl,0)},...o.coverage_counts===void 0?{}:{coverage_counts:{...o.coverage_counts,metrics:{duration:ai(l,c),tokens:wb(r,"tokens"),usd:wb(r,"usd"),brl:wb(r,"brl")}}}}}).sort((i,r)=>r.key.localeCompare(i.key))}function wb(e,t){let n=e.map(i=>i.coverage_counts?.metrics?.[t]);return ai(n.reduce((i,r)=>i+(r?.eligible_runs??0),0),n.reduce((i,r)=>i+(r?.known_runs??0),0))}function w8(e){return el(e)}function E8(e){let t=e.filter(n=>n.phase==="execution"&&n.parent_run_id==null&&z_(n.duration_started_at??n.started_at)&&n.duration_ms!==null&&n.duration_ms>=0);return t.length===0?null:t.reduce((n,i)=>n+i.duration_ms,0)/t.length}function Eb(){return{value:{known_sum:0,unknown:0,complete:!0,coverage_ratio:1},population:ai(0,0)}}function QP(e,t,n){let i=a=>a===null?null:/^\d{4}-\d{2}-\d{2}$/.test(a)?a:Wt(a,"day"),r=i(t),o=i(n);return(r===null||e>=r)&&(o===null||e<=o)}function Ab(e){let t=e.filter(n=>n!==null);return t.length===0?null:t.reduce((n,i)=>n+i,0)}function Tb(e){return e.some(t=>t===null)?null:e.reduce((t,n)=>t+(n??0),0)}function Rb(e,t){return Math.max(0,e-t)}function ai(e,t){return{eligible_runs:e,known_runs:t,unknown_runs:e-t}}zn();function Et(e){let t=e.req.query("from")??null,n=e.req.query("to")??null;return{from:e$(t,"start"),to:e$(n,"end")}}function e$(e,t){if(e===null||!/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let n=t$(e);if(t==="start")return new Date(n).toISOString();let[i,r,o]=e.split("-").map(Number),a=new Date(Date.UTC(i,r-1,o+1)).toISOString().slice(0,10);return new Date(t$(a)-1).toISOString()}function t$(e){let[t,n,i]=e.split("-").map(Number),r=Date.UTC(t,n-1,i),o=r-n$(r);return o=r-n$(o),o}function n$(e){let n=new Intl.DateTimeFormat("en-US",{timeZone:"America/Sao_Paulo",timeZoneName:"longOffset"}).formatToParts(new Date(e)).find(o=>o.type==="timeZoneName")?.value??"GMT",i=/^GMT([+-])(\d{2}):(\d{2})$/.exec(n);if(i===null)return 0;let r=Number(i[2])*60+Number(i[3]);return(i[1]==="+"?1:-1)*r*6e4}zn();ea();function ol(e,t){let n=new Map(e.map(i=>[i.id,i]));for(let i of t.map(r=>Ob(r,t))){let r=n.get(i.id);if(r===void 0){n.set(i.id,i);continue}n.set(i.id,{...i,...r,usage:A8(r.usage,i.usage),provider:r.provider??i.provider,model:r.model==="unknown"?i.model:r.model,reasoning_effort:r.reasoning_effort??i.reasoning_effort,service_tier:r.service_tier??i.service_tier??null,call_count:r.call_count??i.call_count,terminal_call_count:r.terminal_call_count??i.terminal_call_count,...(r.pricing_segments?.length??0)>0?{pricing_segments:r.pricing_segments}:i.pricing_segments===void 0?{}:{pricing_segments:i.pricing_segments},...r.duration_ms!==null&&(r.source_duration_ms===null||r.source_duration_ms===0)?{duration_ms:r.duration_ms,source_duration_ms:null,source_started_at:null,source_finished_at:null,capture_lag_ms:null}:T8(r)})}return[...n.values()]}function A8(e,t){let n=(i,r)=>({...r,...i,tokens:{...r.tokens,...i.tokens,input:i.tokens.input??r.tokens.input,cached_input:i.tokens.cached_input??r.tokens.cached_input,output:i.tokens.output??r.tokens.output,reasoning:i.tokens.reasoning??r.tokens.reasoning,total:i.tokens.total??r.tokens.total},cost:{...r.cost,...i.cost,usd:i.cost.usd??r.cost.usd,brl:i.cost.brl??r.cost.brl}});return{conversation:n(e.conversation,t.conversation),planning:n(e.planning,t.planning),execution:n(e.execution,t.execution),total:n(e.total,t.total),new_work:n(e.new_work,t.new_work),rework:n(e.rework,t.rework)}}function T8(e){return{duration_ms:e.duration_ms,...typeof e.source_duration_ms=="number"?{duration_provenance:"observed"}:e.duration_provenance===void 0?{}:{duration_provenance:e.duration_provenance},estimation_basis:typeof e.source_duration_ms=="number"?null:e.estimation_basis??null,source_duration_ms:e.source_duration_ms??null,source_started_at:e.source_started_at??null,source_finished_at:e.source_finished_at??null,capture_lag_ms:e.capture_lag_ms??null}}function Ob(e,t){let n=Array.isArray(e.usage_segments)?e.usage_segments:[],i=d=>n.length===0||n.some(_=>!R8(_.tokens?.[d]))?null:n.reduce((_,p)=>_+(p.tokens?.[d]??0),0),r=e.quantitative_metrics.tokens_total,o=e.quantitative_metrics.estimated_usd,a=e.quantitative_metrics.estimated_brl,s={events:e.source_event_count,tokens:{input:i("input"),cached_input:i("cached_input"),output:i("output"),reasoning:i("reasoning"),total:r.known_sum},cost:{usd:e.historical_cost?.estimated_usd??o.known_sum,brl:e.historical_cost?.estimated_brl??a.known_sum},coverage:{events:e.source_event_count,tokens:r.complete,usd:o.complete,brl:a.complete}},l={...s,events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},c=e.phase==="execution"?s:l,u=e.invocation_kind==="delegated";return{id:e.run_id,artifact_path:`.agents/records/runs/${e.run_id}`,status:e.status??"completed",phase:e.phase??"execution",entrypoint:e.purpose==="observation"?"observation":e.task_id===null?"conversation":"task",work_type:"new",run_role:u?"subagent":"orchestrator",run_kind:u?"subrun":"run",run_purpose:x8(e.purpose,u),requires_finalizer:!1,parent_run_id:t.find(d=>d.agent_invocation_id===e.parent_agent_invocation_id)?.run_id??null,client:"codex",agent:e.zaip_agent??"unknown",agent_name:e.zaip_agent??"unknown",provider:n.find(d=>typeof d.provider=="string")?.provider??null,model:n.find(d=>typeof d.model=="string")?.model??"unknown",reasoning_effort:n.find(d=>typeof d.reasoning_effort=="string")?.reasoning_effort??null,effective_model:null,effective_reasoning_effort:null,effective_config_mixed:!1,service_tier:n.find(d=>typeof d.service_tier=="string")?.service_tier??null,call_count:e.llm_call_count,terminal_call_count:e.llm_call_count,failed_call_count:e.status==="failed"?e.llm_call_count:0,cancelled_call_count:e.status==="cancelled"?e.llm_call_count:0,conversation_id:e.purpose==="observation"?null:e.agent_invocation_id,execution_id:e.execution_id,task_id:e.task_id,spec_id:e.spec_id,prd_id:e.prd_id,change_id:e.change_id,started_at:e.occurred_at,finished_at:e.status===null?null:e.occurred_at,duration_ms:e.time.duration_ms,source_duration_ms:e.time.duration_ms,source_started_at:null,source_finished_at:e.time.source_latest_at,pricing_segments:n.map(d=>({phase:"execution",provider:d.provider,model:d.model,service_tier:d.service_tier,input_tokens:d.tokens?.input??null,cached_input_tokens:d.tokens?.cached_input??null,output_tokens:d.tokens?.output??null,reasoning_tokens:d.tokens?.reasoning??null,total_tokens:d.tokens?.total??null})),usage:{conversation:l,planning:l,execution:c,total:s,new_work:s,rework:l}}}function x8(e,t){return e==="observation"||e==="intake"||e==="orchestration"||e==="execution"||e==="review"||e==="audit"||e==="finalization"?e:t?"execution":"orchestration"}function R8(e){return typeof e=="number"&&Number.isFinite(e)}function r$(e,t,n){let i=t.trim().toLowerCase();if(!i)return[...e];let r=new Map(n.map(o=>[o.id,o.title]));return e.filter(o=>[o.id,o.task_id,o.task_id===null?null:r.get(o.task_id),o.provider,o.agent,o.agent_name,o.model,o.phase,o.spec_id,o.prd_id,o.execution_id,o.conversation_id].some(a=>a?.toLowerCase().includes(i)))}qe();zn();function Jn(e){return e.req.query("currency")==="USD"?"USD":"BRL"}function tt(e,t){let n=e.req.query(t);return n===void 0||n===""?[]:n.split(",").filter(Boolean)}async function Cb(e,t){let n=new Map,i=new Map,r=1,o=!0;for(;o;){let a=await BC(e,{...t,cache:n,page:r,page_size:500});for(let s of a.summaries)O8(s)&&i.set(s.agent_invocation_id,s);o=a.has_more,r+=1}return[...i.values()]}function O8(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.agent_invocation_id=="string"&&typeof t.root_agent_invocation_id=="string"&&(t.parent_agent_invocation_id===null||typeof t.parent_agent_invocation_id=="string")&&(t.invocation_kind==="orchestrator"||t.invocation_kind==="delegated")&&typeof t.run_id=="string"&&typeof t.quantitative_metrics=="object"&&t.quantitative_metrics!==null&&typeof t.time=="object"&&t.time!==null&&Array.isArray(t.usage_segments)}async function i$(e){try{let t=Di(Nt(await e.readText(".agents/config/agents/catalog.yaml"))).agents;return{agentNames:t.map(n=>n.codex_name),agentNamesById:Object.fromEntries(t.map(n=>[n.id,n.codex_name])),agentNamesByRole:Object.fromEntries(t.map(n=>[n.role,n.codex_name]))}}catch{return{agentNames:[],agentNamesById:{},agentNamesByRole:{}}}}zn();async function al(e){return new Ti(e).readLatestFxRate()}function Ib(e){return["provider","model","agent","phase","status"].every(t=>(e.req.queries(t)?.length??0)===0)}var C8=".agents/dashboard/work-priority.json";async function as(e,t,n,i=!1,r=!1){let o=await il(e,t,n,{overviewOnly:i,includeOverviewChanges:r}),a=I8(o,await Xp(e,Yp(o)));if(i||n.from===null||n.to===null)return a;let s=await Cb(e,{from:n.from,to:n.to});return s.length===0?a:Vp({...a,runs:oi(s$(a.runs,s))})}async function Xp(e,t){try{let n=Nb(JSON.parse(await e.readText(C8)),!1);return t===void 0?n:{...n,item_ids:n.item_ids.filter(i=>t.has(i))}}catch{return{schema_version:1,item_ids:[],updated_at:null}}}function Yp(e){return new Set([...e.prds.map(t=>t.id),...e.specs.map(t=>t.id),...e.tasks.map(t=>t.id)])}function Nb(e,t=!0){let n=typeof e=="object"&&e!==null?e:{};return{schema_version:1,item_ids:Array.isArray(n.item_ids)?[...new Set(n.item_ids.filter(r=>typeof r=="string"&&r.length>0))]:[],updated_at:typeof n.updated_at=="string"&&!t?n.updated_at:new Date().toISOString()}}function I8(e,t){let n=new Map(t.item_ids.map((r,o)=>[r,o])),i=r=>n.get(r)??null;return{...e,prds:e.prds.map(r=>({...r,manual_order:i(r.id)})),specs:e.specs.map(r=>({...r,manual_order:i(r.id)})),tasks:e.tasks.map(r=>({...r,manual_order:i(r.id)}))}}async function os(e,t,n){let i=new Ti(e),[r,o]=await Promise.all([i.readCatalog(),n==="BRL"?i.readLatestFxRate():Promise.resolve(null)]),a=await i$(e);return W_(t,{catalog:r,fxRate:o,currency:n},a)}async function a$(e,t,n){let i=n.req.query("from")??null,r=n.req.query("to")??null;if(i===null||r===null)return os(e,t,Jn(n));let o={providers:tt(n,"provider"),models:tt(n,"model"),zaip_agents:tt(n,"agent"),phases:tt(n,"phase"),statuses:tt(n,"status")},a=await Cb(e,{from:i,to:r,filters:o});if(a.length===0)return os(e,t,Jn(n));let s=oi(s$(t.runs,a));return os(e,{...t,runs:s},Jn(n))}function s$(e,t){let n=new Set(e.map(i=>i.id));return ol(e,t.filter(i=>n.has(i.run_id)))}async function c$(e,t,n,i,r,o){let a=await P8(e,i.from,i.to),{from:s,to:l}=a,c={providers:tt(n,"provider"),models:tt(n,"model"),zaip_agents:tt(n,"agent"),phases:tt(n,"phase"),statuses:tt(n,"status")},u=c.providers.length>0||c.models.length>0||c.zaip_agents.length>0||c.statuses.length>0,[d,_]=await Promise.all([Promise.resolve().then(()=>(ea(),KP)).then(({buildQuickOperationsProjection:k})=>k(e,t,{from:s,to:l},{includeBoardTasks:!0})),e.readText(".agents/records/lifecycle/summary.json").then(k=>JSON.parse(k))]),p=r$(_.run_metrics??[],n.req.query("query")??"",d.tasks).filter(k=>$8(k.finished_at??k.started_at,s,l)).sort((k,P)=>(P.finished_at??P.started_at).localeCompare(k.finished_at??k.started_at)||k.id.localeCompare(P.id)),g=c.phases.length===0?p:p.filter(k=>k.phase!==null&&c.phases.includes(k.phase)),m=await yy(e,{from:s,to:l,filters:c,offset:r,limit:o,...n.req.query("query")?{runIds:new Set(g.map(k=>k.id))}:{}}),f=new Set(m.summaries.map(k=>k.run_id)),v=u?g.filter(k=>f.has(k.id)).map(o$):g.slice(r,r+o).map(o$),S=N8(v,m.summaries),b=oi(S),h=await os(e,{...d,runs:b},Jn(n));return{...h,page_only:!0,overview:{...h.overview,run_count:0,event_count:0,total_tokens:null,estimated_usd:null,estimated_brl:null,recorded_usd:null,recorded_brl:null,average_run_cost_usd:null,average_run_cost_brl:null,average_run_duration_ms:null,known_tokens_per_cycle:null,top_10_token_share:null},groups:{conversations:[],tasks:[],providers:[],agents:[],models:[],daily:[],monthly:[],annual:[]},run_page:{offset:r,limit:o,total:u?null:g.length,has_more:u?m.has_more:r+o<g.length}}}function N8(e,t){let n=new Set(e.map(o=>o.id)),i=ol(e,t.filter(o=>n.has(o.run_id))),r=new Map(i.map(o=>[o.id,o]));return e.map(o=>r.get(o.id)??o)}function o$(e){let t={events:0,tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null},cost:{usd:null,brl:null},coverage:{events:0,tokens:0,usd:0,brl:0}},n={...t,events:e.events??0,tokens:{...t.tokens,total:e.total_tokens},cost:{usd:null,brl:e.currency==="BRL"?e.cost:null},coverage:{events:e.events??0,tokens:e.total_tokens===null?0:1,usd:0,brl:e.cost===null?0:1}};return{id:e.id,artifact_path:`.agents/records/runs/${e.id}`,status:e.status==="failed"||e.status==="cancelled"||e.status==="running"?e.status:"completed",phase:e.phase??"execution",entrypoint:e.entrypoint==="observation"?"observation":e.task_id===null?"conversation":"task",work_type:"new",run_role:e.run_kind==="subrun"?"subagent":"orchestrator",run_kind:e.run_kind??"run",run_purpose:e.run_purpose==="observation"?"observation":"execution",requires_finalizer:!1,parent_run_id:e.parent_run_id,client:"unknown",agent:e.agent??"unknown",agent_name:e.agent_name??e.agent??"unknown",provider:e.provider,model:e.model??"unknown",reasoning_effort:null,effective_model:e.model,effective_reasoning_effort:null,effective_config_mixed:!1,call_count:null,terminal_call_count:null,failed_call_count:0,cancelled_call_count:0,conversation_id:e.entrypoint==="observation"?null:e.conversation_id??e.id,execution_id:e.execution_id,task_id:e.task_id,spec_id:e.spec_id,prd_id:e.prd_id,change_id:e.change_id,started_at:e.started_at,finished_at:e.finished_at,duration_ms:e.duration_ms,source_duration_ms:e.duration_ms,usage:{conversation:t,planning:t,execution:n,total:n,new_work:n,rework:t}}}async function P8(e,t,n){if(t!==null&&n!==null)return{from:t,to:n};let i=await e.readText(".agents/records/lifecycle/summary.json").then(l=>JSON.parse(l)),r=Object.keys(i.periods?.daily??{}).sort(),o=r.at(0),a=r.at(-1),s=new Date().toISOString().slice(0,10);return{from:Kp(t??o??s,"start"),to:Kp(n??a??s,"end")}}function $8(e,t,n){let i=Date.parse(e),r=Date.parse(Kp(t,"start")),o=Date.parse(Kp(n,"end"));return Number.isFinite(i)&&Number.isFinite(r)&&Number.isFinite(o)&&i>=r&&i<=o}function Kp(e,t){return/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T${t==="start"?"00:00:00.000":"23:59:59.999"}Z`:e}ea();ri();function Qp(e){return e.map(t=>({task_id:t.task_id,duration_ms:t.total_duration_ms,total_tokens:t.total_tokens,total_cost_usd:t.total_cost_usd,cost_brl:t.total_cost_brl,run_count:t.total_run_count}))}var sl=e=>typeof e=="number"&&Number.isFinite(e)?e:null,L8=(e,t)=>{let n=String(t);return n==="draft"?e==="prd"?"definition":"planning":n==="ready"||n==="planned"?"ready":n==="active"?"executing":n==="delivered"?"completed":["definition","planning","executing","verifying","completed","blocked","failed","cancelled"].includes(n)?n:"planning"};function Pb(e,t){let n=_=>{let p=e.map(g=>g[_]).filter(g=>typeof g=="number"&&Number.isFinite(g));return p.length===0?null:p.reduce((g,m)=>g+m,0)},i=(_,p)=>sl(_[p])??0,r=n("total_duration"),o=n("total_tokens"),a=n("total_cost_usd"),s=n("total_cost_brl"),l={},c={empty:0,structured:0,rework:0};for(let _ of e){let p=L8(t,_.stage??_.status);l[p]=(l[p]??0)+1;let g=i(_,"rework_run_count")>0?"rework":i(_,"task_count")>0?"structured":"empty";c[g]=(c[g]??0)+1}let u=e.map(_=>({entity_id:String(_.id),title:String(_.title??_.id),duration_ms:sl(_.total_duration),total_tokens:sl(_.total_tokens),total_cost_usd:sl(_.total_cost_usd),cost_brl:sl(_.total_cost_brl),run_count:i(_,"invocation_count")})).toSorted((_,p)=>(p.duration_ms??-1)-(_.duration_ms??-1)||_.entity_id.localeCompare(p.entity_id)).slice(0,5).map(_=>({..._,duration_share:r===null||r===0||_.duration_ms===null?0:_.duration_ms/r})),d=e.flatMap(_=>typeof _.occurred_at=="string"?[_.occurred_at]:[]).toSorted().at(-1)??null;return{status_counts:l,classification_counts:c,entity_count:e.length,total_run_count:e.reduce((_,p)=>_+i(p,"invocation_count"),0),total_duration_ms:r,total_tokens:o,total_cost_usd:a,total_cost_brl:s,average_duration_ms:r===null||e.length===0?null:r/e.length,average_tokens:o===null||e.length===0?null:o/e.length,average_cost_usd:a===null||e.length===0?null:a/e.length,average_cost_brl:s===null||e.length===0?null:s/e.length,latest_created_at:d,top_entities:u}}var u$=require("node:child_process"),d$=require("node:crypto"),$b=require("node:path"),_$=require("node:util");var l$=".agents/dashboard/dashboard.config.json",p$=(0,_$.promisify)(u$.execFile);async function tm(e,t){let n=process.env.ZAIP_DASHBOARD_TITLE?.trim()||"Dashboard ZAIP AIOS",i="auto";try{if(await e.exists(l$)){let r=JSON.parse(await e.readText(l$));typeof r.title=="string"&&r.title.trim()&&(n=r.title.trim()),typeof r.github_repository=="string"&&(i=r.github_repository.trim())}}catch{}if(i.toLowerCase()!=="auto")return{title:n,repository_name:em(i)??""};try{let{stdout:r}=await p$("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",windowsHide:!0});return{title:n,repository_name:em(r)??""}}catch{return{title:n,repository_name:""}}}function em(e){let t=e.trim(),n=t.match(/github\.com(?::|\/)([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i)??t.match(/^([^/:\s]+)\/([^/\s]+?)(?:\.git)?$/);return n?`${n[1]}/${n[2]}`:null}function nm(e){return(0,d$.createHash)("sha256").update(`${(0,$b.resolve)(e)}:dashboard-sqlite`).digest("hex").slice(0,16)}var rm=17e4,ta=class extends Error{constructor(){super(`Open-work reconciliation exceeded ${rm}ms. Canonical records may contain partial changes; the dashboard projection is being refreshed.`),this.name="ReconciliationCommandTimeoutError"}};async function m$(e,t,n={}){let i=x_(t,"reconciliation"),r=n.jobId??i.correlationId;if(i.log("cli_start",{job_id:r,host_terminal_only:n.hostTerminalOnly===!0}),!await e.exists(".agents/runtime/bin/zaip.mjs"))throw i.log("cli_unavailable",{job_id:r}),new Error("ZAIP runtime is unavailable; open work could not be reconciled.");let o=(0,$b.resolve)(t,".agents","runtime","bin","zaip.mjs"),a;try{let s=await p$(process.execPath,[o,"run","reconcile","--open","--json",...n.hostTerminalOnly?["--host-terminal-only"]:[]],{cwd:t,windowsHide:!0,maxBuffer:10485760,timeout:rm,killSignal:"SIGTERM"});a=s.stdout,i.log("cli_output",{job_id:r,stdout:a,stderr:s.stderr})}catch(s){throw i.log("cli_error",{job_id:r,error:s}),typeof s=="object"&&s!==null&&"killed"in s&&s.killed===!0?new ta:s}try{let s=Lb(JSON.parse(a));return i.log("cli_completed",{job_id:r,result:s}),s}catch(s){throw i.log("cli_invalid_result",{job_id:r,error:s,stdout:a}),s}}function Lb(e){let t=new Set,n=new Map,i=new Map,r=new Map,o=(f,v,S)=>{typeof f=="string"&&typeof v=="string"&&r.set(f,{id:f,status:v,reason:typeof S=="string"?S:null})},a=(f,v,S)=>{typeof v=="string"&&f.set(v,typeof S=="string"&&S.trim()?S:null)},s=typeof e=="object"&&e!==null?e:{},l=new Set(["completed","delivered","blocked","cancelled","failed"]),c=Array.isArray(s.reconciliations)?s.reconciliations:[];for(let f of c){if(typeof f!="object"||f===null)continue;let v=f,S=v.error,b=["tasks","changes","executions","specs","prds"].flatMap(h=>Array.isArray(v[h])?v[h]:[]);for(let h of b){if(typeof h!="object"||h===null)continue;let k=h;v.status==="closed"&&l.has(k.status)&&typeof k.id=="string"&&(t.add(k.id),o(k.id,k.status,k.status_reason??S)),k.status==="blocked"?a(n,k.id,k.status_reason??S):v.status==="deferred"&&a(i,k.id,S)}}(Array.isArray(s.runs)?s.runs:[]).forEach(f=>{if(typeof f!="object"||f===null)return;let v=f,S=v.run;typeof S?.run_id=="string"&&(t.add(S.run_id),o(S.run_id,v.status??v.finished?.status,v.finished?.summary))}),(Array.isArray(s.orphaned_executions)?s.orphaned_executions:[]).forEach(f=>{a(n,f,"Execution orphaned after the reconciliation grace period.")}),(Array.isArray(s.orphaned_interaction_executions)?s.orphaned_interaction_executions:[]).forEach(f=>{a(n,f,"Interaction Execution orphaned after the reconciliation grace period.")});for(let f of["orphaned_owner_entities","orphaned_execution_entities"])for(let v of Array.isArray(s[f])?s[f]:[]){if(typeof v!="object"||v===null)continue;let S=v;typeof S.id!="string"||!l.has(S.status)||(t.add(S.id),o(S.id,S.status,S.status_reason),S.status==="blocked"&&a(n,S.id,S.status_reason))}(Array.isArray(s.reconciliation_errors)?s.reconciliation_errors:[]).forEach(f=>{if(typeof f!="object"||f===null)return;let v=f;a(i,v.run_id,v.error)}),(Array.isArray(s.unresolved_running_run_ids)?s.unresolved_running_run_ids:[]).forEach(f=>{a(i,f,"Invocation is still running.")});let m=f=>[...f.entries()].map(([v,S])=>({id:v,reason:S})).sort((v,S)=>v.id.localeCompare(S.id));return{reconciled_ids:[...t].sort(),blocked:m(n),not_reconciled:m(i),outcomes:[...r.values()].sort((f,v)=>f.id.localeCompare(v.id))}}function ss(e){return e.status==="completed"?"completed":e.status==="cancelled"?"cancelled":e.status==="failed"?"failed":e.status==="blocked"?"blocked":e.is_active===!0||e.status==="executing"?"executing":e.status==="verifying"?"verifying":(e.attempt_count??0)>0||e.started_at!=null||e.execution_started===!0?"executing":e.status==="draft"?null:e.status==="planned"?"ready":null}function im(e,t){if(e.lifecycle_status==="cancelled")return"cancelled";if(e.lifecycle_status==="failed")return"failed";if(e.lifecycle_status==="blocked")return"blocked";if(e.lifecycle_status==="delivered"||e.lifecycle_status==="completed")return"completed";if(e.lifecycle_status==="ready")return"ready";if(e.kind==="prd"&&e.lifecycle_status==="draft")return"definition";if(e.kind==="spec"&&e.lifecycle_status==="draft")return"planning";if(e.work_status==="cancelled")return"cancelled";if(e.work_status==="failed")return"failed";if(e.work_status==="blocked")return"blocked";if(e.work_status==="completed")return"completed";if(e.is_active||t.some(n=>e.task_ids.includes(n.id)&&n.is_active))return"executing";if(e.lifecycle_status==="verifying"||e.work_status==="verifying")return"verifying";if(e.work_status==="executing"){let n=t.filter(i=>e.task_ids.includes(i.id));return n.length>0&&n.every(i=>i.status==="verifying"||i.status==="completed")?"verifying":"executing"}return e.lifecycle_status==="active"?"executing":"planning"}qe();function om(e){return/^\.agents\/(?:data|records)\/(?:executions\/.*\/execution\.md|changes\/.*\/change\.md|(?:changes|executions)\/.*\/decisions\/.*\.md)$/.test(e)}function Mb(e){let t=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(e)?.[1];if(t===void 0)return null;try{let n=Nt(t);return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function cs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function pt(e){return typeof e=="string"&&e.length>0?e:null}function cl(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Sn(e){let t=[...new Set(e.filter(n=>typeof n=="string"&&n.length>0&&n!=="unavailable"))];return t.length===0?null:t.length===1?t[0]:"mixed"}zn();var M8=new Intl.DateTimeFormat("en",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"});function bt(e){let t=Object.fromEntries(M8.formatToParts(new Date(e)).filter(n=>n.type!=="literal").map(n=>[n.type,n.value]));return`${t.year}-${t.month}-${t.day}`}var b$=require("node:fs"),Db=require("node:path"),jb=require("node:sqlite");var h$=require("node:crypto"),D8=require("node:sqlite"),am=[["first_fold_viewport_cache","first_fold_viewport_cache:all_time"],["first_fold_all_time_cache","first_fold_all_time_cache:all_time"],["first_fold_all_time_board_cache","first_fold_all_time_board_cache:all_time"],["cost_monitor_summary_cache","cost_monitor_summary_cache:all_time"],["cost_monitor_summary_month_cache","cost_monitor_summary_month_cache:current"],["first_fold_monthly_quick_cache","first_fold_monthly_quick_cache:default"]];function f$(e,t){let n=e.prepare("SELECT payload_json FROM zaip_aios_activities WHERE payload_type=? ORDER BY recorded_at DESC LIMIT 1").get(t);if(typeof n?.payload_json!="string")return null;try{let i=JSON.parse(n.payload_json);return i!==null&&typeof i=="object"?i:null}catch{return null}}function j8(e,t,n){let i="json_extract(payload_json, '$.occurred_day_sp')",r=t&&n?` AND ${i} >= ? AND ${i} <= ?`:"",o=e.prepare(`SELECT json_extract(payload_json, '$.entity_kind') AS kind, COUNT(*) AS count
|
|
364
|
+
FROM zaip_aios_activities WHERE payload_type='work_item'${r} GROUP BY kind`).all(...t&&n?[t,n]:[]);return Object.fromEntries(o.map(a=>[a.kind,Number(a.count)]))}function g$(e,t,n=!1){let i=typeof t.from_day=="string"?t.from_day:void 0,r=typeof t.to_day=="string"?t.to_day:void 0;if(n&&(!i||!r))return!1;let o=j8(e,n?i:void 0,n?r:void 0);return["task","spec","prd"].every(a=>Array.isArray(t.pages?.[a])&&t.pages?.[a].length===(o[a]??0))}function y$(e){if(Number(e.prepare(`SELECT COUNT(DISTINCT payload_type) AS count FROM zaip_aios_activities
|
|
365
365
|
WHERE payload_type IN (${am.map(()=>"?").join(", ")})`).get(...am.map(([r])=>r)).count??0)!==am.length)return!1;let n=f$(e,"first_fold_all_time_board_cache"),i=f$(e,"first_fold_monthly_quick_cache");return n!==null&&i!==null&&g$(e,n)&&g$(e,i,!0)}function v$(e,t){let n=e.prepare(`INSERT INTO zaip_aios_activities(
|
|
366
366
|
activity_row_id, activity_source_kind, activity_key, source_path, source_hash,
|
|
367
367
|
recorded_at, run_role, root_run_id, payload_type, payload_json
|
|
368
368
|
) VALUES (?, 'technical_payload', ?, ?, '', datetime('now'), 'technical', 'technical', ?, ?)`);for(let[i,r]of am){let o=e.prepare("SELECT activity_row_id,payload_json FROM zaip_aios_activities WHERE payload_type=? AND activity_key=?").get(i,r);if(o){o.payload_json!==t[i]&&e.prepare("UPDATE zaip_aios_activities SET payload_json=?,recorded_at=datetime('now') WHERE activity_row_id=?").run(t[i],o.activity_row_id);continue}n.run(`TECH-${(0,h$.randomUUID)().toLowerCase()}`,r,`sqlite://${i}/${r.split(":")[1]}`,i,t[i])}}var Ub=".local/sqlite/zaip-aios-dashboard.sqlite",Gn="85",ll=["zaip_aios_activities","zaip_dim_llm_model","zaip_dim_provider","zaip_dim_zaip_agent","cost_invocation_dimension_facts","cost_group_daily_projection","cost_group_entity_projection","developer_cost_projection","operations_work_projection"],ls=["zaip_activities_agent_run","zaip_activities_relationships","zaip_activities_task_day","zaip_activities_spec_day","zaip_activities_prd_day","zaip_activities_agent","zaip_activities_run_id","zaip_activities_run_hierarchy","zaip_activities_period","zaip_activities_period_invocation","zaip_activities_status","zaip_activities_payload","zaip_activities_duration_activity","zaip_activities_file_path","zaip_activities_work_item_identity","cost_dimension_facts_day_model","cost_dimension_facts_day_provider","cost_dimension_facts_invocation","cost_group_daily_projection_lookup","cost_group_entity_projection_lookup","developer_cost_projection_lookup"],ul=["zaip_vw_read_model_metadata","zaip_vw_operations_overview","zaip_vw_cost_overview","zaip_vw_cost_models","zaip_vw_cost_providers","zaip_vw_operations_agent_invocations"],S$=2*36e5,Fb=48*36e5;function si(e){return(0,Db.resolve)(process.env.ZAIP_SQLITE_DB_PATH??(0,Db.resolve)(e,Ub))}function sm(e){if(!(0,b$.existsSync)(e))return new Map;let t;try{t=new jb.DatabaseSync(e,{readOnly:!0});let n=t.prepare("SELECT source_path, source_hash, mtime_ms, ctime_ms, size_bytes, file_identity FROM zaip_vw_read_model_source_state").all();return new Map(n.flatMap(i=>{let r=typeof i.source_path=="string"?i.source_path:null,o=typeof i.source_hash=="string"?i.source_hash:null,a=typeof i.file_identity=="string"?i.file_identity:null,s=typeof i.mtime_ms=="number"?i.mtime_ms:typeof i.mtime_ms=="string"?Number(i.mtime_ms):Number.NaN,l=typeof i.ctime_ms=="number"?i.ctime_ms:typeof i.ctime_ms=="string"?Number(i.ctime_ms):Number.NaN;return r===null||o===null||a===null||!Number.isFinite(s)||!Number.isFinite(l)||typeof i.size_bytes!="number"?[]:[[r,{source:r,mtimeMs:s,ctimeMs:l,size:i.size_bytes,contentHash:o,fileIdentity:a}]]}))}catch{return new Map}finally{t?.close()}}function na(e,t={}){let n=new jb.DatabaseSync(e,{readOnly:!0});try{let i=t.integrity==="quick"?"quick_check":"integrity_check",r=n.prepare(`PRAGMA ${i}`).get();if(r[i]!=="ok")throw new Error(`SQLite ${i} failed for ${e}: ${r[i]??"unknown"}`);let o=n.prepare("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view', 'index')").all(),a=o.filter(f=>f.type==="table").map(f=>f.name).sort(),s=[...ll].sort();if(a.length!==s.length||a.some((f,v)=>f!==s[v]))throw new Error(`SQLite schema ${Gn} requires the complete persisted table contract; found ${a.join(", ")||"none"}`);let l=n.prepare("PRAGMA table_info(operations_work_projection)").all(),c=new Set(l.flatMap(f=>typeof f.name=="string"?[f.name]:[])),u=["task_count","rework_run_count"].filter(f=>!c.has(f));if(u.length>0)throw new Error(`SQLite schema ${Gn} requires operations_work_projection columns: ${u.join(", ")}`);let d=new Set(o.map(f=>f.name)),_=ul.filter(f=>!d.has(f));if(_.length>0)throw new Error(`SQLite schema is missing required views: ${_.join(", ")}`);let p=o.filter(f=>f.type==="view").map(f=>f.name);if(p.some(f=>!f.startsWith("zaip_vw_")))throw new Error("SQLite persisted views must use the zaip_vw_ namespace");let g=ls.filter(f=>!d.has(f));if(g.length>0)throw new Error(`SQLite schema is missing required indexes: ${g.join(", ")}`);let m=n.prepare("SELECT value FROM zaip_vw_read_model_metadata WHERE key = ?").get("schema_version")?.value;if(m!==Gn)throw new Error(`SQLite schema version must be ${Gn}; found ${m??"missing"}`);return{schemaVersion:m,tableCount:a.length,viewCount:p.length,indexCount:o.filter(f=>f.type==="index"&&!f.name.startsWith("sqlite_")).length}}finally{n.close()}}function cm(e){let t=e.prepare("SELECT name FROM sqlite_master WHERE type='index'").all(),n=new Set(t.map(i=>i.name));return ls.every(i=>n.has(i))&&y$(e)}function lm(e){let t=new Set;for(let r of e){t.add(r.startMs),t.add(r.endMs);for(let o=r.startMs;o<r.endMs;){let a=Date.parse(`${bt(new Date(o).toISOString())}T03:00:00.000Z`)+864e5;if(a>=r.endMs)break;t.add(a),o=a}}let n=[...t].sort((r,o)=>r-o),i=new Map;for(let r=0;r<n.length-1;r+=1){let o=n[r],a=n[r+1],s=e.filter(u=>u.startMs<a&&u.endMs>o);if(s.length===0||a<=o)continue;let l=(a-o)/s.length,c=bt(new Date(o).toISOString());for(let u of s){let d=`${u.activityRowId}:${c}`,_=i.get(d);i.set(d,{activityRowId:u.activityRowId,day:c,value:(_?.value??0)+l})}}return[...i.values()]}function k$(){let e=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date),t=Object.fromEntries(e.map(i=>[i.type,i.value])),n=`${t.year}-${t.month}-${t.day}`;return{from:`${t.year}-${t.month}-01`,to:n}}function w$(e){let t=[],n=[],i=[];for(let r of e){if(!om(r.path))continue;let o=Mb(r.content);if(o===null)continue;let a=pt(o.id),s=pt(o.created_at);if(!(a===null||s===null||Number.isNaN(Date.parse(s)))){if(/^\.agents\/(?:data|records)\/executions\/.*\/execution\.md$/.test(r.path)){let l=cs(o.origin),c=pt(l?.type),u=c==="interaction"?pt(l?.conversation_id):c==="task"?pt(l?.task_id):c==="spec"?pt(l?.spec_id):c==="prd"?pt(l?.prd_id):null;t.push({id:a,status:pt(o.status),kind:pt(o.kind),originType:c,originId:u,createdAt:s,finishedAt:pt(o.finished_at),sourcePath:r.path});continue}if(/^\.agents\/(?:data|records)\/changes\/.*\/change\.md$/.test(r.path)){let l=cs(o.source),c=pt(l?.type),u=c==="task"?pt(l?.task_id):c==="spec"?pt(l?.spec_id):c==="prd"?pt(l?.prd_id):null;if(c===null||u===null)continue;n.push({id:a,title:pt(o.title)??a,status:pt(o.status)??"unclassified",risk:pt(o.risk)??"unclassified",sourceType:c,sourceId:u,sourceSpecId:pt(l?.spec_id),sourcePrdId:pt(l?.prd_id),requirementIds:cl(o.requirement_ids),acceptanceIds:cl(o.acceptance_ids),taskIds:cl(o.task_ids),result:pt(o.result),createdAt:s,sourcePath:r.path});continue}if(/^\.agents\/(?:data|records)\/(changes|executions)\/.*\/decisions\/.*\.md$/.test(r.path)){let l=o.origin,c=o.scope_type,u=pt(o.scope_id);if(l!=="human"&&l!=="agent"||c!=="change"&&c!=="execution"||u===null)continue;i.push({id:a,title:pt(o.title)??a,origin:l,scopeType:c,scopeId:u,createdAt:s,sourcePath:r.path})}}}return{executions:t,changes:n,decisions:i}}function zb(e){let t=new Map;for(let n of e){let i=/^\.agents\/(?:data|records)\/(tasks|specs|prds|changes|executions|conversations)\//.exec(n.path);if(i===null)continue;let r=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(n.content)?.[1];if(r===void 0)continue;let o=l=>{let c=new RegExp(`^${l}:\\s*(.+?)\\s*$`,"m").exec(r)?.[1]?.trim();return c===void 0||c==="null"?null:c.replace(/^['"]|['"]$/g,"")},a=o("id");if(a===null)continue;let s=i[1]?.slice(0,-1);s!==void 0&&t.set(`${s}:${a}`,{kind:s,id:a,title:o("title"),status:o("status"),stage:s==="task"?ss({status:o("status"),spec_id:o("spec_id"),started_at:o("started_at"),attempt_count:Number(o("attempt_count")??0)}):o("stage"),risk:o("risk"),priority:o("priority"),specId:o("spec_id"),prdId:o("prd_id"),changeId:o("change_id"),occurredAt:o("created_at")??o("started_at")??o("recorded_at"),creationRunId:o("creation_run_id"),completedRunId:o("completed_run_id")})}return t}function E$(e,t){let n=new Map;for(let i of(e??"").split(/^ {2}- id: /m).slice(1)){let r=i.slice(0,i.indexOf(`
|
|
369
|
-
`)).trim(),o=/\bcodex_name:\s*([^\s#]+)/.exec(i)?.[1]??null;if(o===null)continue;let a=/persona:\s*\{\s*nome:\s*([^,}\s]+),\s*cargo:\s*([^,}\s]+)\s*\}/.exec(i),s=/\brole:\s*([^\s#]+)/.exec(i)?.[1]??null,l={catalogId:r,persona:a?.[1]??null,job:a?.[2]??null,role:s},c=new Set([o,r]);for(let u of i.matchAll(/^ {8}- kind:\s*(?:id|codex_name|codex_task_name)\s*\r?\n {10}value:\s*([^\s#]+)/gm)){let d=u[1];d!==void 0&&c.add(d)}for(let u of[...c])u.startsWith("agent-")&&c.add(`zaip-${u}`);for(let u of c)n.set(u,l)}return/^ {2}- id:\s*codex\s*$/m.test(t??"")&&n.set("codex",{catalogId:"client:codex",persona:"codex",job:"client_host",role:"host"}),n}function A$(e){return e.prd_id!==null&&e.execution_id===null||e.spec_id!==null&&e.execution_id===null||e.phase==="planning"||e.purpose==="planning"?"planning":e.execution_id!==null||e.task_id!==null||e.phase==="execution"||e.purpose==="implementation"?"development":"conversation"}function kn(e,t){let n=e.map(i=>i.tokens[t]).filter(i=>typeof i=="number");return n.length===0?null:n.reduce((i,r)=>i+r,0)}function us(e,t,n){return e==="openai"||e==="anthropic"?e:e==="unavailable"||t==="unavailable"||t===null?null:U_(t,n,"")}function
|
|
369
|
+
`)).trim(),o=/\bcodex_name:\s*([^\s#]+)/.exec(i)?.[1]??null;if(o===null)continue;let a=/persona:\s*\{\s*nome:\s*([^,}\s]+),\s*cargo:\s*([^,}\s]+)\s*\}/.exec(i),s=/\brole:\s*([^\s#]+)/.exec(i)?.[1]??null,l={catalogId:r,persona:a?.[1]??null,job:a?.[2]??null,role:s},c=new Set([o,r]);for(let u of i.matchAll(/^ {8}- kind:\s*(?:id|codex_name|codex_task_name)\s*\r?\n {10}value:\s*([^\s#]+)/gm)){let d=u[1];d!==void 0&&c.add(d)}for(let u of[...c])u.startsWith("agent-")&&c.add(`zaip-${u}`);for(let u of c)n.set(u,l)}return/^ {2}- id:\s*codex\s*$/m.test(t??"")&&n.set("codex",{catalogId:"client:codex",persona:"codex",job:"client_host",role:"host"}),n}function A$(e){return e.prd_id!==null&&e.execution_id===null||e.spec_id!==null&&e.execution_id===null||e.phase==="planning"||e.purpose==="planning"?"planning":e.execution_id!==null||e.task_id!==null||e.phase==="execution"||e.purpose==="implementation"?"development":"conversation"}function kn(e,t){let n=e.map(i=>i.tokens[t]).filter(i=>typeof i=="number");return n.length===0?null:n.reduce((i,r)=>i+r,0)}function us(e,t,n){return e==="openai"||e==="anthropic"?e:e==="unavailable"||t==="unavailable"||t===null?null:U_(t,n,"")}function U8(e){return typeof e.duration_ms=="number"&&(e.duration_provenance==="observed"||e.duration_provenance==="reconciled"||e.duration_provenance==="legacy_inferred")}function F8(e){let t=e.flatMap(r=>{let o=r.source_started_at,a=r.source_finished_at,s=typeof o=="string"?Date.parse(o):Number.NaN,l=typeof a=="string"?Date.parse(a):Number.NaN;return typeof o=="string"&&typeof a=="string"&&Number.isFinite(s)&&Number.isFinite(l)&&l>s&&l-s<=Fb?[{start:o,end:a,startMs:s,endMs:l}]:[]});if(t.length===0)return null;let n=t.reduce((r,o)=>o.startMs<r.startMs?o:r),i=t.reduce((r,o)=>o.endMs>r.endMs?o:r);return i.endMs-n.startMs<=Fb?{start:n.start,end:i.end,duration:i.endMs-n.startMs}:null}function T$(e,t){let n=F8(e);if(n!==null)return{source:n.duration,effective:n.duration,provenance:"reconciled",sourceStartedAt:n.start,sourceFinishedAt:n.end};if(typeof t.finished?.duration_ms=="number"&&t.finished.duration_provenance!=="estimated"&&t.finished.duration_provenance!=="unavailable")return{source:t.finished.duration_ms,effective:t.finished.duration_ms,provenance:t.finished.duration_provenance??"observed",sourceStartedAt:null,sourceFinishedAt:null};let i=e.filter(U8);if(i.length>0){let a=i.reduce((l,c)=>l+(c.duration_ms??0),0),s=Sn(i.map(l=>l.duration_provenance))??"observed";return{source:a,effective:a,provenance:s,sourceStartedAt:null,sourceFinishedAt:null}}let r=Date.parse(t.run.occurred_at),o=typeof t.finished?.occurred_at=="string"?Date.parse(t.finished.occurred_at):Number.NaN;return Number.isFinite(r)&&Number.isFinite(o)&&o>r&&o-r<=S$?{source:null,effective:o-r,provenance:"reconciled",sourceStartedAt:null,sourceFinishedAt:null}:{source:null,effective:null,provenance:null,sourceStartedAt:null,sourceFinishedAt:null}}function x$(e){return e.flatMap(t=>{try{return[$o.parse(JSON.parse(t.content))]}catch{return[]}}).sort((t,n)=>n.as_of.localeCompare(t.as_of))[0]??null}function um(e,t,n,i){let r=0,o=0,a=!1,s=!1,l=!1,c=[],u=[];for(let _ of e){if(typeof _.cost.usd=="number"&&(r+=_.cost.usd,a=!0),typeof _.cost.brl=="number"&&(o+=_.cost.brl,s=!0),typeof _.cost.usd=="number"&&typeof _.cost.brl=="number"||_.tokens.total===null)continue;if(_.tokens.total===0){a=!0,s=!0;continue}let p=_.model??t.run.model;if(p===null||p==="unavailable")continue;let g=Mo({provider:us(_.provider,p,t.run.client),model:p,usage:_.tokens,catalog:n,fxRate:i,serviceTier:_.runtime?.service_tier??null});typeof _.cost.usd!="number"&&g.estimated_usd!==null&&(r+=g.estimated_usd,a=!0,l=!0),typeof _.cost.brl!="number"&&g.estimated_brl!==null&&(o+=g.estimated_brl,s=!0,l=!0),g.pricing_model!==null&&c.push(g.pricing_model),g.pricing_source!==null&&u.push(g.pricing_source)}let d=kn(e,"total");return{usd:a?Math.round(r*1e6)/1e6:null,brl:s?Math.round(o*1e6)/1e6:null,method:d===0?"zero_no_llm_usage":l?"token_pricing_estimate":a||s?"canonical_recorded":null,pricingModel:Sn(c),pricingSource:Sn(u),fxRate:s?i?.rate??null:null}}function z8(e,t){if(t===null)return null;let n=t.toLowerCase(),i=r=>{let o=r.toLowerCase();if(n===o)return!0;let a=n.slice(o.length);return a.startsWith("@")||a.startsWith(":")||a.startsWith("/")||/^-\d{4}-\d{2}-\d{2}(?:$|[.:@/])/.test(a)};return e.models.find(r=>i(r.id)||r.aliases.some(o=>i(o)))??null}function R$(e,t,n,i){let r=e.model??t.run.model,o=us(e.provider,r,t.run.client),a=e.runtime?.service_tier??null,s=z8(n,r),l=r===null?null:Mo({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:a}),c=r===null?null:Mo({provider:o,model:r,usage:e.tokens,catalog:n,fxRate:i,serviceTier:"default"}),u=s?.long_context_threshold_tokens!==null&&s?.long_context_threshold_tokens!==void 0&&(e.tokens.input??0)>s.long_context_threshold_tokens,d=a==="priority"||a==="fast",_=d&&!u,p=s?_?s.priority_input_per_million_usd??null:s.input_per_million_usd:null,g=s?_?s.priority_cached_input_per_million_usd??null:s.cached_input_per_million_usd:null,m=s?_?s.priority_output_per_million_usd??null:s.output_per_million_usd:null,f=s?_?s.priority_reasoning_per_million_usd??s.priority_output_per_million_usd??null:s.reasoning_per_million_usd??s.output_per_million_usd:null,v=l?.estimated_usd!==null&&l!==null?l:c,S=v?.estimated_usd??null,b=c?.estimated_usd??null,h=e.cost.usd,k=h??S,P=e.cost.brl??l?.estimated_brl??(k!==null&&i!==null?Math.round(k*i.rate*1e6)/1e6:null);return{provider:o,model:r,serviceTier:a,uncachedInputTokens:e.tokens.input===null?null:Math.max(e.tokens.input-(e.tokens.cached_input??0),0),visibleOutputTokens:e.tokens.output===null?null:Math.max(e.tokens.output-(e.tokens.reasoning??0),0),inputRate:p,cachedRate:g,outputRate:m,reasoningRate:f,contextInputMultiplier:s?u?s.long_context_input_multiplier:1:null,contextOutputMultiplier:s?u?s.long_context_output_multiplier:1:null,speedCostMultiplier:S!==null&&b!==null&&b>0?Math.round(S/b*1e3)/1e3:null,pricingScenario:d&&u?"standard_long_context_fallback":d?"priority":"standard",standardUsd:b,speedUpliftUsd:S!==null&&b!==null?Math.round((S-b)*1e6)/1e6:null,inputUsd:v?.input_usd??null,cachedInputUsd:v?.cached_input_usd??null,outputUsd:v?.output_usd??null,reasoningUsd:v?.reasoning_usd??null,calculatedUsd:S,recordedUsd:h,effectiveUsd:k,effectiveBrl:P,varianceUsd:h!==null&&S!==null?Math.round((h-S)*1e6)/1e6:null,pricingModel:v?.pricing_model??s?.id??null,pricingSource:v?.pricing_source??s?.source_label??null,fxRate:e.cost.fx_rate??i?.rate??null}}function st(e){return e==null?null:/^\d{4}-\d{2}-\d{2}$/.test(e)?e:bt(e)}function qb(e,t){let n=e.map(i=>i[t]).filter(i=>typeof i=="number"&&Number.isFinite(i));return n.length===0?null:n.reduce((i,r)=>i+r,0)}function O$(e,t){let n=e.includes("/artifacts/evidence/")?"evidence":e.includes("/artifacts/validations/")||e.includes("/artifacts/tests/")?"validation":null;if(n===null)return null;let i=/^---\r?\n([\s\S]*?)\r?\n---/.exec(t)?.[1]??"",r=a=>{let s=new RegExp(`^${a}:\\s*['"]?(.+?)['"]?\\s*$`,"m").exec(i)?.[1]?.trim();return s===void 0||s==="null"?null:s},o=r("observed_at")??r("executed_at")??r("created_at")??r("recorded_at");return o===null||Number.isNaN(Date.parse(o))?null:{kind:n,id:r("id")??e.slice(e.lastIndexOf("/")+1,-3),occurredAt:o,occurredDaySp:bt(o),taskId:r("task_id"),changeId:r("change_id"),runId:r("run_id")}}var Qb=require("node:sqlite");qe();var q8=["prd_count","spec_count","task_count","test_count","evidence_count"],dm=()=>({prd_count:0,spec_count:0,task_count:0,test_count:0,evidence_count:0});function V8(e,t){let n=["a.payload_type IS NULL","a.run_id IS NOT NULL","a.zaip_agent IS NOT NULL"],i=[];for(let p of["from","to"])t[p]&&(n.push(`a.occurred_day_sp ${p==="from"?">=":"<="} ?`),i.push(t[p].slice(0,10)));for(let p of["agent","phase","status"])t[p]&&(n.push(`a.${p==="agent"?"zaip_agent":p}=?`),i.push(t[p]));t.risk&&(n.push("EXISTS (SELECT 1 FROM zaip_aios_activities t WHERE t.payload_type='work_item' AND json_extract(t.payload_json,'$.entity_kind')='task' AND json_extract(t.payload_json,'$.id')=a.task_id AND json_extract(t.payload_json,'$.risk')=?)"),i.push(t.risk)),(t.priority||t.workType)&&n.push("0"),t.origin&&n.push(t.origin==="prd"?"a.prd_id IS NOT NULL":t.origin==="spec"?"a.prd_id IS NULL AND a.spec_id IS NOT NULL":t.origin==="task"?"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NOT NULL":"a.prd_id IS NULL AND a.spec_id IS NULL AND a.task_id IS NULL");let r=[];for(let p of["provider","model"])t[p]&&(r.push(`COALESCE(u.${p},'unavailable')=?`),i.push(t[p]));r.length&&n.push(`EXISTS (SELECT 1 FROM invocation_usage u WHERE u.agent_invocation_id=a.agent_invocation_id AND ${r.join(" AND ")})`),t.query&&(n.push("(a.zaip_agent LIKE ? OR a.zaip_agent_persona LIKE ? OR a.zaip_agent_job LIKE ?)"),i.push(...Array(3).fill(`%${t.query}%`)));let o=e.prepare(`SELECT a.run_id, MIN(a.zaip_agent) AS agent FROM zaip_aios_activities a WHERE ${n.join(" AND ")} GROUP BY a.run_id HAVING COUNT(DISTINCT a.zaip_agent)=1`).all(...i),a=new Map(o.map(p=>[p.run_id,p.agent])),s=new Map,l=new Set,c=t.from?.slice(0,10)??"0000-01-01",u=t.to?.slice(0,10)??"9999-12-31",d=e.prepare(`WITH files AS (
|
|
370
370
|
SELECT json_extract(payload_json,'$.path') path,
|
|
371
371
|
json_extract(payload_json,'$.artifact_kind') artifact_kind,
|
|
372
372
|
json_extract(payload_json,'$.artifact_id') artifact_id,
|
|
@@ -388,7 +388,7 @@ ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest
|
|
|
388
388
|
`).all();for(let p of d){if(!p.day||p.day<c||p.day>u)continue;let g=a.get(p.run_id);if(!g)continue;let m=`${p.kind}:${p.id}`;if(l.has(m))continue;l.add(m);let f=s.get(g)??dm(),v=`${p.kind}_count`;f[v]=(f[v]??0)+1,s.set(g,f)}let _=e.prepare(`SELECT a.zaip_agent AS agent,
|
|
389
389
|
COUNT(DISTINCT NULLIF(trim(a.task_id),'')) AS task_count
|
|
390
390
|
FROM zaip_aios_activities a WHERE ${n.join(" AND ")}
|
|
391
|
-
GROUP BY a.zaip_agent`).all(...i);for(let p of _){let g=s.get(p.agent)??dm();g.task_count=p.task_count,s.set(p.agent,g)}return s}function C$(e,t,n){let i=
|
|
391
|
+
GROUP BY a.zaip_agent`).all(...i);for(let p of _){let g=s.get(p.agent)??dm();g.task_count=p.task_count,s.set(p.agent,g)}return s}function C$(e,t,n){let i=V8(e,t);for(let r of n.rows)r.tasks_active=r.task_count,Object.assign(r,i.get(String(r.key))??dm()),r.validation_count=r.test_count;if(n.totals){let r=dm();for(let o of i.values())for(let a of q8)r[a]=r[a]===null||o[a]===null?null:r[a]+o[a];Object.assign(n.totals,r,{validation_count:r.test_count})}}function I$(e,t,n,i){let r=performance.now(),o=i();if(e){let a=Math.round(performance.now()-r);t(n,82,`${n}: ${a}ms.`),process.stderr.write(`${JSON.stringify({event:"dashboard_sqlite_first_fold",phase:n,elapsed_ms:a})}
|
|
392
392
|
`)}return o}function Vb(e,t){let n=performance.now(),i=t();return process.env.ZAIP_DASHBOARD_LAUNCH_PROGRESS==="1"&&process.stderr.write(`${JSON.stringify({event:"dashboard_sqlite_first_fold_query",phase:e,elapsed_ms:Math.round(performance.now()-n)})}
|
|
393
393
|
`),i}var At=(e,t=0)=>typeof e=="number"?e:t,St=e=>typeof e=="number"?e:null;function dl(e,t){let n=e.prepare("SELECT payload_json FROM zaip_aios_activities WHERE payload_type=? ORDER BY recorded_at DESC LIMIT 1").get(t);if(typeof n?.payload_json!="string")return null;try{return JSON.parse(n.payload_json)}catch{return null}}function P$(e){return["specs","prds"].every(t=>{let n=e.macro_metrics?.[t];if(n==null||!Number.isSafeInteger(n.entity_count)||n.entity_count<0||!N$(n.status_counts)||!N$(n.classification_counts))return!1;let i=r=>Object.values(r).reduce((o,a)=>o+a,0);return i(n.status_counts)===n.entity_count&&i(n.classification_counts)===n.entity_count})}function N$(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>Number.isSafeInteger(t)&&t>=0)}function $$(e,t,n){let i=dl(e,"first_fold_all_time_cache");if(i!==null&&P$(i))return i;let r=(c,u)=>Vb(c,u),o=n===void 0?e.prepare("SELECT * FROM zaip_vw_first_fold_overview_all_time").get():null,a=n===void 0?e.prepare("SELECT status, task_count FROM zaip_vw_first_fold_task_status_all_time").all():null,s=n===void 0?e.prepare("SELECT risk, task_count FROM zaip_vw_first_fold_task_risk_all_time").all():null,l=r("first_fold_all_time_top_tasks",()=>e.prepare("SELECT * FROM zaip_vw_first_fold_top_tasks_all_time ORDER BY rank").all());return{aggregate:n?.aggregate??{days:typeof o?.start_day=="string"&&typeof o.end_day=="string"?t():0,start_day:typeof o?.start_day=="string"?o.start_day:null,end_day:typeof o?.end_day=="string"?o.end_day:null,task_count:At(o?.task_count),completed_task_count:At(o?.completed_task_count),spec_count:At(o?.spec_count),completed_spec_count:At(o?.completed_spec_count),prd_count:At(o?.prd_count),completed_prd_count:At(o?.completed_prd_count),total_run_count:At(o?.total_run_count),agent_invocation_count:At(o?.agent_invocation_count),llm_call_count:St(o?.llm_call_count),duration_ms:St(o?.total_duration_ms),total_tokens:St(o?.total_tokens),total_cost_usd:St(o?.total_cost_usd),cost_brl:St(o?.total_cost_brl),execution_day_count:At(o?.execution_day_count),latest_task_created_at:typeof o?.latest_task_created_at=="string"?o.latest_task_created_at:null},task_status_counts:n?.task_status_counts??Object.fromEntries(a?.map(c=>[c.status,Number(c.task_count)])??[]),task_risk_counts:n?.task_risk_counts??Object.fromEntries(s?.map(c=>[c.risk,Number(c.task_count)])??[]),task_metrics:n?{average_duration_ms_per_task:n.aggregate.task_count===0||n.aggregate.duration_ms===null?null:n.aggregate.duration_ms/n.aggregate.task_count,average_tokens_per_task:n.aggregate.task_count===0||n.aggregate.total_tokens===null?null:n.aggregate.total_tokens/n.aggregate.task_count,average_cost_usd_per_task:n.aggregate.task_count===0||n.aggregate.total_cost_usd===null?null:n.aggregate.total_cost_usd/n.aggregate.task_count,average_cost_brl_per_task:n.aggregate.task_count===0||n.aggregate.cost_brl===null?null:n.aggregate.cost_brl/n.aggregate.task_count,latest_task_created_at:n.aggregate.latest_task_created_at}:(()=>{let c=e.prepare("SELECT * FROM zaip_vw_first_fold_task_metrics_all_time").get();return{average_duration_ms_per_task:St(c.average_duration_ms_per_task),average_tokens_per_task:St(c.average_tokens_per_task),average_cost_usd_per_task:St(c.average_cost_usd_per_task),average_cost_brl_per_task:St(c.average_cost_brl_per_task),latest_task_created_at:typeof c.latest_task_created_at=="string"?c.latest_task_created_at:null}})(),top_tasks:l,macro_metrics:Wb(e)}}function L$(e,t){let n=dl(e,"first_fold_viewport_cache");if(n!==null)return n;let i=performance.now(),r=e.prepare(`WITH totals AS (
|
|
394
394
|
SELECT SUM(CASE WHEN activity_source_kind='agent_run' THEN 1 ELSE 0 END) AS agent_invocation_count,
|
|
@@ -435,10 +435,10 @@ ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest
|
|
|
435
435
|
)
|
|
436
436
|
SELECT totals.*, run_totals.*, duration_totals.*, bounds.*, item_totals.*, task_status.*, task_risk.*
|
|
437
437
|
FROM totals CROSS JOIN run_totals CROSS JOIN duration_totals CROSS JOIN bounds
|
|
438
|
-
CROSS JOIN item_totals CROSS JOIN task_status CROSS JOIN task_risk`).get();return process.env.ZAIP_DASHBOARD_PROFILE_FIRST_FOLD==="1"&&(t.viewport_overview=Math.round((performance.now()-i)*10)/10,console.info(JSON.stringify({event:"dashboard_first_fold_select",select:"viewport_overview",elapsed_ms:t.viewport_overview}))),{aggregate:{days:At(r.day_count),start_day:typeof r.start_day=="string"?r.start_day:null,end_day:typeof r.end_day=="string"?r.end_day:null,task_count:At(r.task_count),completed_task_count:At(r.completed_task_count),spec_count:At(r.spec_count),completed_spec_count:At(r.completed_spec_count),prd_count:At(r.prd_count),completed_prd_count:At(r.completed_prd_count),total_run_count:At(r.total_run_count),agent_invocation_count:At(r.agent_invocation_count),llm_call_count:St(r.llm_call_count),duration_ms:St(r.total_duration_ms),total_tokens:St(r.total_tokens),total_cost_usd:St(r.total_cost_usd),cost_brl:St(r.total_cost_brl),execution_day_count:At(r.execution_day_count),latest_task_created_at:typeof r.latest_task_created_at=="string"?r.latest_task_created_at:null},task_status_counts:typeof r.task_status_json=="string"?JSON.parse(r.task_status_json):{},task_risk_counts:typeof r.task_risk_json=="string"?JSON.parse(r.task_risk_json):{}}}function M$(e,t){return dl(e,"first_fold_all_time_board_cache")??t()}function D$(e){return e.prepare("SELECT * FROM zaip_vw_first_fold_top_tasks_all_time ORDER BY rank").all()}function j$(e,t,n){let i=t;if(i===void 0){let u=dl(e,"first_fold_monthly_quick_cache");i=u!==null&&typeof u.from_day=="string"&&typeof u.to_day=="string"&&u.aggregate!==void 0&&u.pages!==void 0&&Array.isArray(u.top_tasks)?u:null}if(i===null)return{cache:i,result:null};let r=n.from?.slice(0,10)??null,o=n.to?.slice(0,10)??null,a=r===i.from_day&&o===i.to_day,s=r===i.from_day&&o!==null&&o>i.to_day&&o.slice(0,7)===i.from_day.slice(0,7),l=i.source_latest_day===null||i.source_latest_day<=i.to_day;if(a||s&&l)return{cache:i,result:i};let c=i.source_latest_day===null?i.from_day.slice(0,7):i.source_latest_day.slice(0,7);return r===null||o===null||r.slice(0,7)<=c?{cache:i,result:null}:{cache:i,result:{from_day:r,to_day:o,source_latest_day:i.source_latest_day,aggregate:{days:0,total_run_count:0,agent_invocation_count:0,llm_call_count:null,duration_ms:null,total_tokens:null,cost_brl:null,execution_day_count:0},pages:{task:[],spec:[],prd:[]},top_tasks:[]}}}function Wb(e){let t=dl(e,"first_fold_all_time_cache");if(t!==null&&P$(t))return t.macro_metrics;let n=(r,o)=>Vb(r,o),i=r=>{let o=n(`first_fold_${r}_status`,()=>e.prepare(`SELECT stage, entity_count FROM zaip_vw_first_fold_${r}_status_all_time`).all()),a=n(`first_fold_${r}_classification`,()=>e.prepare(`SELECT classification, entity_count FROM zaip_vw_first_fold_${r}_classification_all_time`).all()),s=n(`first_fold_${r}_metrics`,()=>e.prepare(`SELECT * FROM zaip_vw_first_fold_${r}_metrics_all_time`).get()),l=n(`first_fold_${r}_top_entities`,()=>e.prepare(`SELECT * FROM zaip_vw_first_fold_top_${r}s_all_time ORDER BY rank`).all());return{status_counts:Object.fromEntries(o.map(c=>[c.stage,Number(c.entity_count)])),classification_counts:Object.fromEntries(a.map(c=>[c.classification,Number(c.entity_count)])),entity_count:At(s.entity_count),total_run_count:At(s.total_run_count),total_duration_ms:St(s.total_duration_ms),total_tokens:St(s.total_tokens),total_cost_usd:St(s.total_cost_usd),total_cost_brl:St(s.total_cost_brl),average_duration_ms:St(s.average_duration_ms),average_tokens:St(s.average_tokens),average_cost_usd:St(s.average_cost_usd),average_cost_brl:St(s.average_cost_brl),latest_created_at:typeof s.latest_created_at=="string"?s.latest_created_at:null,top_entities:l}};return{specs:i("spec"),prds:i("prd")}}function
|
|
438
|
+
CROSS JOIN item_totals CROSS JOIN task_status CROSS JOIN task_risk`).get();return process.env.ZAIP_DASHBOARD_PROFILE_FIRST_FOLD==="1"&&(t.viewport_overview=Math.round((performance.now()-i)*10)/10,console.info(JSON.stringify({event:"dashboard_first_fold_select",select:"viewport_overview",elapsed_ms:t.viewport_overview}))),{aggregate:{days:At(r.day_count),start_day:typeof r.start_day=="string"?r.start_day:null,end_day:typeof r.end_day=="string"?r.end_day:null,task_count:At(r.task_count),completed_task_count:At(r.completed_task_count),spec_count:At(r.spec_count),completed_spec_count:At(r.completed_spec_count),prd_count:At(r.prd_count),completed_prd_count:At(r.completed_prd_count),total_run_count:At(r.total_run_count),agent_invocation_count:At(r.agent_invocation_count),llm_call_count:St(r.llm_call_count),duration_ms:St(r.total_duration_ms),total_tokens:St(r.total_tokens),total_cost_usd:St(r.total_cost_usd),cost_brl:St(r.total_cost_brl),execution_day_count:At(r.execution_day_count),latest_task_created_at:typeof r.latest_task_created_at=="string"?r.latest_task_created_at:null},task_status_counts:typeof r.task_status_json=="string"?JSON.parse(r.task_status_json):{},task_risk_counts:typeof r.task_risk_json=="string"?JSON.parse(r.task_risk_json):{}}}function M$(e,t){return dl(e,"first_fold_all_time_board_cache")??t()}function D$(e){return e.prepare("SELECT * FROM zaip_vw_first_fold_top_tasks_all_time ORDER BY rank").all()}function j$(e,t,n){let i=t;if(i===void 0){let u=dl(e,"first_fold_monthly_quick_cache");i=u!==null&&typeof u.from_day=="string"&&typeof u.to_day=="string"&&u.aggregate!==void 0&&u.pages!==void 0&&Array.isArray(u.top_tasks)?u:null}if(i===null)return{cache:i,result:null};let r=n.from?.slice(0,10)??null,o=n.to?.slice(0,10)??null,a=r===i.from_day&&o===i.to_day,s=r===i.from_day&&o!==null&&o>i.to_day&&o.slice(0,7)===i.from_day.slice(0,7),l=i.source_latest_day===null||i.source_latest_day<=i.to_day;if(a||s&&l)return{cache:i,result:i};let c=i.source_latest_day===null?i.from_day.slice(0,7):i.source_latest_day.slice(0,7);return r===null||o===null||r.slice(0,7)<=c?{cache:i,result:null}:{cache:i,result:{from_day:r,to_day:o,source_latest_day:i.source_latest_day,aggregate:{days:0,total_run_count:0,agent_invocation_count:0,llm_call_count:null,duration_ms:null,total_tokens:null,cost_brl:null,execution_day_count:0},pages:{task:[],spec:[],prd:[]},top_tasks:[]}}}function Wb(e){let t=dl(e,"first_fold_all_time_cache");if(t!==null&&P$(t))return t.macro_metrics;let n=(r,o)=>Vb(r,o),i=r=>{let o=n(`first_fold_${r}_status`,()=>e.prepare(`SELECT stage, entity_count FROM zaip_vw_first_fold_${r}_status_all_time`).all()),a=n(`first_fold_${r}_classification`,()=>e.prepare(`SELECT classification, entity_count FROM zaip_vw_first_fold_${r}_classification_all_time`).all()),s=n(`first_fold_${r}_metrics`,()=>e.prepare(`SELECT * FROM zaip_vw_first_fold_${r}_metrics_all_time`).get()),l=n(`first_fold_${r}_top_entities`,()=>e.prepare(`SELECT * FROM zaip_vw_first_fold_top_${r}s_all_time ORDER BY rank`).all());return{status_counts:Object.fromEntries(o.map(c=>[c.stage,Number(c.entity_count)])),classification_counts:Object.fromEntries(a.map(c=>[c.classification,Number(c.entity_count)])),entity_count:At(s.entity_count),total_run_count:At(s.total_run_count),total_duration_ms:St(s.total_duration_ms),total_tokens:St(s.total_tokens),total_cost_usd:St(s.total_cost_usd),total_cost_brl:St(s.total_cost_brl),average_duration_ms:St(s.average_duration_ms),average_tokens:St(s.average_tokens),average_cost_usd:St(s.average_cost_usd),average_cost_brl:St(s.average_cost_brl),latest_created_at:typeof s.latest_created_at=="string"?s.latest_created_at:null,top_entities:l}};return{specs:i("spec"),prds:i("prd")}}function W8(e){if(e===null||typeof e!="object")return!1;let t=e.pages;return t===null||typeof t!="object"?!1:["task","spec","prd"].every(n=>Array.isArray(t[n]))}function B8(e,t){return t!=="task"?t:e.kind==="task"||e.kind==="standalone-task"?e.kind:typeof e.spec_id=="string"&&e.spec_id.length>0||e.origin==="spec"||e.origin==="prd"?"task":"standalone-task"}function Z8(e,t,n){if(n.kind&&n.kind!=="all"&&!(n.kind==="all-tasks"?t==="task"||t==="standalone-task":t===n.kind))return!1;if(n.query){let i=n.query.toLowerCase();if(!String(e.id??"").toLowerCase().includes(i)&&!String(e.title??"").toLowerCase().includes(i))return!1}return!(n.status&&e.stage!==n.status||n.risk&&e.risk!==n.risk||n.origin&&(t==="prd"||t==="spec"||typeof e.origin!="string")||n.origin&&e.origin!==n.origin)}function F$(e,t){if(!W8(t)||(e.from||e.to)&&!(typeof t.from_day=="string"))return null;let n=["task","spec","prd"].flatMap(a=>t.pages[a].map(s=>({...s,kind:B8(s,a)}))).filter(a=>Z8(a,String(a.kind),e)).sort((a,s)=>String(s.occurred_at??"").localeCompare(String(a.occurred_at??""))||String(s.id??"").localeCompare(String(a.id??""))),i=Math.min(200,Math.max(1,e.limit??50)),r=Math.max(0,e.offset??0),o=n.slice(r,r+i);return{offset:r,limit:i,total_count:n.length,has_more:r+o.length<n.length,rows:o}}var Zb="canonical.spec_id IS NOT NULL",Hb="(COALESCE(canonical.change_id, (SELECT change.id FROM canonical_changes change, json_each(change.task_ids_json) task WHERE task.value = canonical.id ORDER BY change.created_at DESC, change.id DESC LIMIT 1)))",_m=`(SELECT change.source_type FROM canonical_changes change WHERE change.id=${Hb})`,Bb=`(${Zb} OR COALESCE(${_m} IN ('spec', 'prd'), 0))`;function z$(e){let t=[],n=[];if(e.from&&(t.push("canonical.occurred_day_sp >= ?"),n.push(e.from.slice(0,10))),e.to&&(t.push("canonical.occurred_day_sp <= ?"),n.push(e.to.slice(0,10))),e.query&&(t.push("(work.id LIKE ? OR work.title LIKE ?)"),n.push(`%${e.query}%`,`%${e.query}%`)),e.status&&(t.push("canonical.stage = ?"),n.push(e.status)),e.risk&&(t.push("canonical.risk = ?"),n.push(e.risk)),e.origin){t.push("canonical.entity_kind = 'task'");let r=e.origin==="spec"?Zb:e.origin==="task"?`NOT ${Zb}`:"0";t.push(`(${_m} = ? OR (${_m} IS NULL AND ${r}))`),n.push(e.origin)}return e.kind==="prd"||e.kind==="spec"?(t.push("canonical.entity_kind = ?"),n.push(e.kind)):(e.kind==="all-tasks"||e.kind==="task"||e.kind==="standalone-task")&&(t.push("canonical.entity_kind = 'task'"),e.kind!=="all-tasks"&&t.push(e.kind==="task"?Bb:`NOT ${Bb}`)),{source:"operations_work_kanban work JOIN canonical_work_items canonical ON canonical.entity_kind=work.entity_kind AND canonical.id=work.id",where:t.length===0?"":` WHERE ${t.join(" AND ")}`,values:n,select:`SELECT work.*, canonical.stage, canonical.prd_id,
|
|
439
439
|
COALESCE(canonical.spec_id, (SELECT COALESCE(change.source_spec_id, CASE WHEN change.source_type='spec' THEN change.source_id END) FROM canonical_changes change WHERE change.id=${Hb})) AS spec_id,
|
|
440
440
|
${Hb} AS change_id, ${_m} AS origin,
|
|
441
|
-
CASE WHEN canonical.entity_kind='task' THEN CASE WHEN ${Bb} THEN 'task' ELSE 'standalone-task' END ELSE canonical.entity_kind END AS kind`}}function q$(e){return e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='operations_work_projection' LIMIT 1").get()!==void 0}function
|
|
441
|
+
CASE WHEN canonical.entity_kind='task' THEN CASE WHEN ${Bb} THEN 'task' ELSE 'standalone-task' END ELSE canonical.entity_kind END AS kind`}}function q$(e){return e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='operations_work_projection' LIMIT 1").get()!==void 0}function H8(e){let t=[],n=[];if(e.from&&(t.push("occurred_day_sp >= ?"),n.push(e.from.slice(0,10))),e.to&&(t.push("occurred_day_sp <= ?"),n.push(e.to.slice(0,10))),e.query&&(t.push("(id LIKE ? OR title LIKE ?)"),n.push(`%${e.query}%`,`%${e.query}%`)),e.status&&(t.push("stage = ?"),n.push(e.status)),e.risk&&(t.push("risk = ?"),n.push(e.risk)),e.origin){t.push("entity_kind = 'task'");let i=e.origin==="spec"?"spec_id IS NOT NULL":e.origin==="task"?"spec_id IS NULL":"0";t.push(`(origin = ? OR (origin IS NULL AND ${i}))`),n.push(e.origin)}return e.kind==="prd"||e.kind==="spec"?(t.push("entity_kind = ?"),n.push(e.kind)):e.kind==="all-tasks"?t.push("entity_kind = 'task'"):(e.kind==="task"||e.kind==="standalone-task")&&(t.push("kind = ?"),n.push(e.kind)),{where:t.length===0?"":` WHERE ${t.join(" AND ")}`,values:n}}function V$(e,t){let n=Math.min(200,Math.max(1,t.limit??50)),i=Math.max(0,t.offset??0);if(q$(e)){let s=H8(t),l=Number(e.prepare(`SELECT COUNT(*) AS count FROM operations_work_projection${s.where}`).get(...s.values).count),c=e.prepare(`SELECT * FROM operations_work_projection${s.where} ORDER BY occurred_at DESC, id DESC LIMIT ? OFFSET ?`).all(...s.values,n,i);return{offset:i,limit:n,total_count:l,has_more:i+c.length<l,rows:c}}let r=z$(t),o=Number(e.prepare(`SELECT COUNT(*) AS count FROM ${r.source}${r.where}`).get(...r.values).count),a=e.prepare(`${r.select} FROM ${r.source}${r.where} ORDER BY work.occurred_at DESC, work.id DESC LIMIT ? OFFSET ?`).all(...r.values,n,i);return{offset:i,limit:n,total_count:o,has_more:i+a.length<o,rows:a}}function U$(e){let t=e.entity_kind??e.kind;return t==="task"||t==="standalone-task"?"task":t==="spec"||t==="prd"?t:null}function W$(e,t,n){let i=t.flatMap(c=>{let u=U$(c),d=typeof c.id=="string"&&c.id.length>0?c.id:null;return u&&d?[{entityKind:u,id:d}]:[]});if(i.length===0)return t.map(c=>({...c,developers:[]}));let r=i.flatMap(({entityKind:c,id:u})=>[c,u]),o=n.from?.slice(0,10)??null,a=n.to?.slice(0,10)??null,s=e.prepare(`WITH page_items(entity_kind, id) AS (VALUES ${i.map(()=>"(?, ?)").join(", ")}),
|
|
442
442
|
identified_developers AS (
|
|
443
443
|
SELECT page_items.entity_kind, page_items.id,
|
|
444
444
|
CAST(activity.developer_account_id AS TEXT) AS account_id,
|
|
@@ -819,7 +819,7 @@ ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest
|
|
|
819
819
|
a.occurred_at, a.task_id, a.attributed_token_active_ms AS duration_ms, a.source_event_count, a.total_tokens, a.cost_usd, a.cost_brl
|
|
820
820
|
FROM activities a LEFT JOIN tasks activity_task ON activity_task.id=a.task_id LEFT JOIN zaip_dim_zaip_agent d ON d.zaip_agent = a.zaip_agent
|
|
821
821
|
WHERE ${o.join(" AND ")}
|
|
822
|
-
)`,d=Math.min(200,Math.max(1,n.limit??50)),_=Math.max(0,n.offset??0),p=Number(e.database.prepare(`${u} SELECT COUNT(DISTINCT key) AS count FROM agent_facts`).get(...l,...a).count),g=e.database.prepare(`${u} SELECT COUNT(*) AS invocation_count, COUNT(DISTINCT task_id) AS task_count, SUM(duration_ms) AS total_duration, SUM(CASE WHEN duration_ms IS NULL THEN 1 ELSE 0 END) AS duration_unknown, SUM(CASE WHEN duration_ms IS NULL THEN 0 ELSE duration_ms END) AS duration_known, SUM(source_event_count) AS source_event_count, SUM(total_tokens) AS total_tokens, SUM(cost_usd) AS total_cost_usd, SUM(cost_brl) AS total_cost_brl FROM agent_facts`).get(...l,...a),m=e.database.prepare(`${u} SELECT key, key AS label, COALESCE(MAX(persona), MAX(catalog_persona)) AS persona, COALESCE(MAX(job), MAX(catalog_job)) AS job, MAX(occurred_at) AS latest_started_at, COUNT(*) AS invocation_count, COUNT(DISTINCT task_id) AS task_count, SUM(duration_ms) AS total_duration, SUM(CASE WHEN duration_ms IS NULL THEN 1 ELSE 0 END) AS duration_unknown, SUM(CASE WHEN duration_ms IS NULL THEN 0 ELSE duration_ms END) AS duration_known, SUM(source_event_count) AS source_event_count, SUM(total_tokens) AS total_tokens, SUM(cost_usd) AS total_cost_usd, SUM(cost_brl) AS total_cost_brl FROM agent_facts GROUP BY key ORDER BY total_cost_brl DESC, key LIMIT ? OFFSET ?`).all(...l,...a,d,_);return{data_source:"sqlite_read_model",view:t,offset:_,limit:d,total_count:p,has_more:_+m.length<p,totals:g,rows:m}}function Xb(e){if(!e)return null;if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=new Date(e);if(Number.isNaN(t.valueOf()))return null;let n=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t);return`${n.find(i=>i.type==="year")?.value}-${n.find(i=>i.type==="month")?.value}-${n.find(i=>i.type==="day")?.value}`}function pL(e,t){let n=Xb(t.from),i=Xb(t.to),r=a=>a.replace(/[A-Z]/g,s=>s.toLowerCase()),o=t.query?r(t.query):null;return e.filter(a=>{if(o!==null&&![a.agent_invocation_id,a.task_id,a.execution_id].some(c=>typeof c=="string"&&r(c).includes(o)))return!1;let s=a.source_started_at??a.source_occurred_at??a.occurred_at,l=typeof s=="string"?Xb(s):null;return l!==null&&(n===null||l>=n)&&(i===null||l<=i)})}function mL(e,t){let n=[...new Set(t.flatMap(o=>typeof o.task_id=="string"?[o.task_id]:[]))],i=n.length===0?[]:e.prepare("SELECT id, priority, risk, status AS task_status, title AS task_title FROM tasks WHERE id IN ("+n.map(()=>"?").join(",")+")").all(...n),r=new Map(i.map(o=>[o.id,o]));return t.map(o=>{let a=r.get(o.task_id);return{...o,priority:a?.priority??null,risk:a?.risk??null,task_status:a?.task_status??null,task_title:a?.task_title??null}})}function fL(e,t,n){let i=!n.from&&!n.to&&!n.query&&!n.status&&!n.risk&&!n.provider&&!n.model&&!n.agent&&!n.phase&&!n.origin&&!n.workType&&!n.priority;if(t==="cost_monitor_agent_invocations"&&!/[\0%_]/.test(n.query??"")&&!n.status&&!n.risk&&!n.provider&&!n.model&&!n.agent&&!n.phase&&!n.origin&&!n.workType&&!n.priority){let s=e.technicalPayloadRows("cost_agent_invocation_projection_v1"),l=pL(s,n);if(s.length>0){let c=Math.min(200,Math.max(1,n.limit??100)),u=Math.max(0,n.offset??0),d=l.slice(u,u+c);return{data_source:"sqlite_read_model",view:t,offset:u,limit:c,total_count:l.length,has_more:u+d.length<l.length,rows:n.query?mL(e.database,d):d}}}let a={cost_monitor_zaip_agents:"agent",cost_monitor_executions:"execution",cost_monitor_tasks:"task",cost_monitor_conversations:"conversation"}[t];if(i&&a!==void 0){let s=e.technicalPayloadRows("cost_dimension_aggregate_v1").filter(u=>u.dimension===a),l=s.filter(u=>u.row_kind==="row").map(u=>t==="cost_monitor_zaip_agents"?{key:u.key,label:u.label,persona:u.persona,job:u.job,latest_started_at:u.latest_started_at,invocation_count:u.invocation_count,task_count:u.task_count,total_duration:u.total_duration,duration_unknown:u.duration_unknown,duration_known:u.duration_known,source_event_count:u.source_event_count,total_tokens:u.total_tokens,total_cost_usd:u.total_cost_usd,total_cost_brl:u.total_cost_brl}:{id:u.id,key:u.key,title:u.title,status:u.status,risk:u.risk,first_day:u.first_day,last_day:u.last_day,occurred_at:u.occurred_at,invocation_count:u.invocation_count,llm_call_count:u.llm_call_count,total_duration:u.total_duration,total_input_tokens:u.total_input_tokens,total_cached_input_tokens:u.total_cached_input_tokens,total_output_tokens:u.total_output_tokens,total_reasoning_tokens:u.total_reasoning_tokens,total_tokens:u.total_tokens,total_cost_usd:u.total_cost_usd,total_cost_brl:u.total_cost_brl}).sort((u,d)=>Number(d.total_cost_brl??-1)-Number(u.total_cost_brl??-1)||String(u.key??"").localeCompare(String(d.key??""))),c=s.find(u=>u.row_kind==="totals");if(l.length>0&&c!==void 0){let u=Math.min(200,Math.max(1,n.limit??50)),d=Math.max(0,n.offset??0),_=l.slice(d,d+u),p=t!=="cost_monitor_zaip_agents"?{entity_count:c.entity_count,invocation_count:c.invocation_count,total_duration:c.total_duration,total_tokens:c.total_tokens,total_cost_usd:c.total_cost_usd,total_cost_brl:c.total_cost_brl}:{invocation_count:c.invocation_count,task_count:c.task_count,total_duration:c.total_duration,duration_unknown:c.duration_unknown,duration_known:c.duration_known,source_event_count:c.source_event_count,total_tokens:c.total_tokens,total_cost_usd:c.total_cost_usd,total_cost_brl:c.total_cost_brl};return{data_source:"sqlite_read_model",view:t,offset:d,limit:u,total_count:l.length,has_more:d+_.length<l.length,totals:p,rows:_}}}return null}var
|
|
822
|
+
)`,d=Math.min(200,Math.max(1,n.limit??50)),_=Math.max(0,n.offset??0),p=Number(e.database.prepare(`${u} SELECT COUNT(DISTINCT key) AS count FROM agent_facts`).get(...l,...a).count),g=e.database.prepare(`${u} SELECT COUNT(*) AS invocation_count, COUNT(DISTINCT task_id) AS task_count, SUM(duration_ms) AS total_duration, SUM(CASE WHEN duration_ms IS NULL THEN 1 ELSE 0 END) AS duration_unknown, SUM(CASE WHEN duration_ms IS NULL THEN 0 ELSE duration_ms END) AS duration_known, SUM(source_event_count) AS source_event_count, SUM(total_tokens) AS total_tokens, SUM(cost_usd) AS total_cost_usd, SUM(cost_brl) AS total_cost_brl FROM agent_facts`).get(...l,...a),m=e.database.prepare(`${u} SELECT key, key AS label, COALESCE(MAX(persona), MAX(catalog_persona)) AS persona, COALESCE(MAX(job), MAX(catalog_job)) AS job, MAX(occurred_at) AS latest_started_at, COUNT(*) AS invocation_count, COUNT(DISTINCT task_id) AS task_count, SUM(duration_ms) AS total_duration, SUM(CASE WHEN duration_ms IS NULL THEN 1 ELSE 0 END) AS duration_unknown, SUM(CASE WHEN duration_ms IS NULL THEN 0 ELSE duration_ms END) AS duration_known, SUM(source_event_count) AS source_event_count, SUM(total_tokens) AS total_tokens, SUM(cost_usd) AS total_cost_usd, SUM(cost_brl) AS total_cost_brl FROM agent_facts GROUP BY key ORDER BY total_cost_brl DESC, key LIMIT ? OFFSET ?`).all(...l,...a,d,_);return{data_source:"sqlite_read_model",view:t,offset:_,limit:d,total_count:p,has_more:_+m.length<p,totals:g,rows:m}}function Xb(e){if(!e)return null;if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=new Date(e);if(Number.isNaN(t.valueOf()))return null;let n=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t);return`${n.find(i=>i.type==="year")?.value}-${n.find(i=>i.type==="month")?.value}-${n.find(i=>i.type==="day")?.value}`}function pL(e,t){let n=Xb(t.from),i=Xb(t.to),r=a=>a.replace(/[A-Z]/g,s=>s.toLowerCase()),o=t.query?r(t.query):null;return e.filter(a=>{if(o!==null&&![a.agent_invocation_id,a.task_id,a.execution_id].some(c=>typeof c=="string"&&r(c).includes(o)))return!1;let s=a.source_started_at??a.source_occurred_at??a.occurred_at,l=typeof s=="string"?Xb(s):null;return l!==null&&(n===null||l>=n)&&(i===null||l<=i)})}function mL(e,t){let n=[...new Set(t.flatMap(o=>typeof o.task_id=="string"?[o.task_id]:[]))],i=n.length===0?[]:e.prepare("SELECT id, priority, risk, status AS task_status, title AS task_title FROM tasks WHERE id IN ("+n.map(()=>"?").join(",")+")").all(...n),r=new Map(i.map(o=>[o.id,o]));return t.map(o=>{let a=r.get(o.task_id);return{...o,priority:a?.priority??null,risk:a?.risk??null,task_status:a?.task_status??null,task_title:a?.task_title??null}})}function fL(e,t,n){let i=!n.from&&!n.to&&!n.query&&!n.status&&!n.risk&&!n.provider&&!n.model&&!n.agent&&!n.phase&&!n.origin&&!n.workType&&!n.priority;if(t==="cost_monitor_agent_invocations"&&!/[\0%_]/.test(n.query??"")&&!n.status&&!n.risk&&!n.provider&&!n.model&&!n.agent&&!n.phase&&!n.origin&&!n.workType&&!n.priority){let s=e.technicalPayloadRows("cost_agent_invocation_projection_v1"),l=pL(s,n);if(s.length>0){let c=Math.min(200,Math.max(1,n.limit??100)),u=Math.max(0,n.offset??0),d=l.slice(u,u+c);return{data_source:"sqlite_read_model",view:t,offset:u,limit:c,total_count:l.length,has_more:u+d.length<l.length,rows:n.query?mL(e.database,d):d}}}let a={cost_monitor_zaip_agents:"agent",cost_monitor_executions:"execution",cost_monitor_tasks:"task",cost_monitor_conversations:"conversation"}[t];if(i&&a!==void 0){let s=e.technicalPayloadRows("cost_dimension_aggregate_v1").filter(u=>u.dimension===a),l=s.filter(u=>u.row_kind==="row").map(u=>t==="cost_monitor_zaip_agents"?{key:u.key,label:u.label,persona:u.persona,job:u.job,latest_started_at:u.latest_started_at,invocation_count:u.invocation_count,task_count:u.task_count,total_duration:u.total_duration,duration_unknown:u.duration_unknown,duration_known:u.duration_known,source_event_count:u.source_event_count,total_tokens:u.total_tokens,total_cost_usd:u.total_cost_usd,total_cost_brl:u.total_cost_brl}:{id:u.id,key:u.key,title:u.title,status:u.status,risk:u.risk,first_day:u.first_day,last_day:u.last_day,occurred_at:u.occurred_at,invocation_count:u.invocation_count,llm_call_count:u.llm_call_count,total_duration:u.total_duration,total_input_tokens:u.total_input_tokens,total_cached_input_tokens:u.total_cached_input_tokens,total_output_tokens:u.total_output_tokens,total_reasoning_tokens:u.total_reasoning_tokens,total_tokens:u.total_tokens,total_cost_usd:u.total_cost_usd,total_cost_brl:u.total_cost_brl}).sort((u,d)=>Number(d.total_cost_brl??-1)-Number(u.total_cost_brl??-1)||String(u.key??"").localeCompare(String(d.key??""))),c=s.find(u=>u.row_kind==="totals");if(l.length>0&&c!==void 0){let u=Math.min(200,Math.max(1,n.limit??50)),d=Math.max(0,n.offset??0),_=l.slice(d,d+u),p=t!=="cost_monitor_zaip_agents"?{entity_count:c.entity_count,invocation_count:c.invocation_count,total_duration:c.total_duration,total_tokens:c.total_tokens,total_cost_usd:c.total_cost_usd,total_cost_brl:c.total_cost_brl}:{invocation_count:c.invocation_count,task_count:c.task_count,total_duration:c.total_duration,duration_unknown:c.duration_unknown,duration_known:c.duration_known,source_event_count:c.source_event_count,total_tokens:c.total_tokens,total_cost_usd:c.total_cost_usd,total_cost_brl:c.total_cost_brl};return{data_source:"sqlite_read_model",view:t,offset:d,limit:u,total_count:l.length,has_more:d+_.length<l.length,totals:p,rows:_}}}return null}var J8={task:{title:"entity.title",status:"entity.status",risk:"entity.risk"},spec:{title:"entity.title",status:"entity.status",risk:"entity.risk"},prd:{title:"entity.title",status:"entity.status",risk:"entity.risk"},execution:{title:"grouped.group_value",status:"entity.status",risk:"NULL"},conversation:{title:"grouped.group_value",status:"entity.status",risk:"NULL"}};function gL(e,t,n,i){let r=J8[n],o=["group_kind = ?","group_value IS NOT NULL"],a=[n];i.from&&(o.push("day >= ?"),a.push(i.from.slice(0,10))),i.to&&(o.push("day <= ?"),a.push(i.to.slice(0,10))),i.query&&(o.push("group_value LIKE ?"),a.push(`%${i.query}%`));let s=o.join(" AND "),l=fm(i)?"cost_group_daily_projection":"cost_monitor_group_daily_cache",c=Number(e.prepare(`SELECT COUNT(DISTINCT group_value) AS count FROM ${l} WHERE ${s}`).get(...a).count),u=e.prepare(`SELECT COUNT(DISTINCT group_value) AS entity_count,
|
|
823
823
|
COALESCE(SUM(invocation_count), 0) AS invocation_count,
|
|
824
824
|
ROUND(SUM(total_duration)) AS total_duration,
|
|
825
825
|
SUM(total_tokens) AS total_tokens,
|
|
@@ -1148,7 +1148,7 @@ ${"stderr"in e?String(e.stderr??""):""}`:String(e)).includes("Lifecycle manifest
|
|
|
1148
1148
|
recorded_at, run_role, root_run_id, payload_type, payload_json
|
|
1149
1149
|
) VALUES (?, 'technical_payload', ?, ?, ?, ?, 'technical', 'technical', 'parsed_source', ?)`).run(`TECH-${(0,eS.randomUUID)()}`,o,n,i,new Date().toISOString(),JSON.stringify(s)),s}};function vm(e,t,n){let i=new Map(e.prepare("SELECT activity_row_id,activity_key,payload_json FROM zaip_aios_activities WHERE payload_type=?").all(t).map(l=>[l.activity_key,l])),r=e.prepare(`INSERT INTO zaip_aios_activities(
|
|
1150
1150
|
activity_row_id,activity_source_kind,activity_key,source_path,source_hash,recorded_at,run_role,root_run_id,payload_type,payload_json,occurred_day_sp
|
|
1151
|
-
) VALUES (?,'technical_payload',?,?,'',?,'technical','technical',?,?,?)`),o=e.prepare("UPDATE zaip_aios_activities SET payload_json=?,recorded_at=?,occurred_day_sp=? WHERE activity_row_id=?"),a=e.prepare("DELETE FROM zaip_aios_activities WHERE activity_row_id=?"),s=typeof n=="string"?e.prepare(n).all():n;for(let l of s){let c=`${t}:${l.row_key}`,u=i.get(c),d=l.payload_json;if(t==="source_state"&&u){let _=JSON.parse(d),p=JSON.parse(u.payload_json);_.source_hash===p.source_hash&&(_.last_processed_at=p.last_processed_at),d=JSON.stringify(_)}u?d!==u.payload_json&&o.run(d,new Date().toISOString(),l.occurred_day_sp??null,u.activity_row_id):r.run(`TECH-${(0,eS.randomUUID)()}`,c,`sqlite://${t}`,new Date().toISOString(),t,d,l.occurred_day_sp??null),i.delete(c)}for(let l of i.values())a.run(l.activity_row_id)}function OL(e,t,n){let i=new Set(n),r=[...e,...t].filter(a=>i.has(a.activityRowId)),o=!0;for(;o;){o=!1;for(let a of t)i.has(a.activityRowId)||r.some(s=>a.startMs<s.endMs&&a.endMs>s.startMs)&&(i.add(a.activityRowId),r.push(a),o=!0)}return{ids:i,intervals:t.filter(a=>i.has(a.activityRowId))}}var
|
|
1151
|
+
) VALUES (?,'technical_payload',?,?,'',?,'technical','technical',?,?,?)`),o=e.prepare("UPDATE zaip_aios_activities SET payload_json=?,recorded_at=?,occurred_day_sp=? WHERE activity_row_id=?"),a=e.prepare("DELETE FROM zaip_aios_activities WHERE activity_row_id=?"),s=typeof n=="string"?e.prepare(n).all():n;for(let l of s){let c=`${t}:${l.row_key}`,u=i.get(c),d=l.payload_json;if(t==="source_state"&&u){let _=JSON.parse(d),p=JSON.parse(u.payload_json);_.source_hash===p.source_hash&&(_.last_processed_at=p.last_processed_at),d=JSON.stringify(_)}u?d!==u.payload_json&&o.run(d,new Date().toISOString(),l.occurred_day_sp??null,u.activity_row_id):r.run(`TECH-${(0,eS.randomUUID)()}`,c,`sqlite://${t}`,new Date().toISOString(),t,d,l.occurred_day_sp??null),i.delete(c)}for(let l of i.values())a.run(l.activity_row_id)}function OL(e,t,n){let i=new Set(n),r=[...e,...t].filter(a=>i.has(a.activityRowId)),o=!0;for(;o;){o=!1;for(let a of t)i.has(a.activityRowId)||r.some(s=>a.startMs<s.endMs&&a.endMs>s.startMs)&&(i.add(a.activityRowId),r.push(a),o=!0)}return{ids:i,intervals:t.filter(a=>i.has(a.activityRowId))}}var G8=performance.now();function wn(e,t,n){process.env.ZAIP_DASHBOARD_LAUNCH_PROGRESS==="1"&&process.stderr.write(`${JSON.stringify({event:"dashboard_sqlite_rebuild_progress",phase:e,percent:t,detail:n,elapsed_ms:Math.round(performance.now()-G8)})}
|
|
1152
1152
|
`)}function tS(e,t){let n=wn,i=(_,p)=>I$(process.env.ZAIP_DASHBOARD_LAUNCH_PROGRESS==="1",n,_,p),r=new ct(e,t),o=i("first_fold_viewport",()=>r.firstFoldViewportAllTime()),a=i("first_fold_all_time",()=>r.firstFoldAllTime()),s=i("first_fold_board",()=>r.firstFoldBoardAllTime()),l=i("first_fold_cost_summary",()=>r.costMonitorSummaryAggregate({from:null,to:null})),c=k$(),u=i("first_fold_cost_summary_month",()=>r.costMonitorSummaryAggregate(c)),d={from_day:c.from,to_day:c.to,source_latest_day:i("first_fold_latest_day",()=>r.firstFoldRelevantLatestDay()),aggregate:i("first_fold_month_aggregate",()=>r.firstFoldAggregate(c)),pages:{task:pm(s.pages.task,c.from,c.to),spec:pm(s.pages.spec,c.from,c.to),prd:pm(s.pages.prd,c.from,c.to)},top_tasks:i("first_fold_month_top_tasks",()=>r.topTasks(c))};r.close(),v$(t,{first_fold_viewport_cache:JSON.stringify(o),first_fold_all_time_cache:JSON.stringify(a),first_fold_all_time_board_cache:JSON.stringify(s),cost_monitor_summary_cache:JSON.stringify(l),cost_monitor_summary_month_cache:JSON.stringify({...c,aggregate:u}),first_fold_monthly_quick_cache:JSON.stringify(d)})}var jL=require("node:crypto");ri();function En(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!["unavailable","unknown","mixed"].includes(t.toLowerCase())?t:null}function CL(e,t){let n=["model","provider"],i=new Set(e.prepare("SELECT provider FROM zaip_dim_provider").all().map(C=>C.provider)),r=e.prepare(`SELECT activity_row_id, agent_invocation_id, task_id, duration_ms,
|
|
1153
1153
|
source_event_count, provider, model, total_tokens, cost_usd, cost_brl, run_id,
|
|
1154
1154
|
activity_source_kind, zaip_agent, zaip_agent_persona, zaip_agent_job,
|
|
@@ -2316,12 +2316,12 @@ current_day=`)[1]&&(u.exec("DELETE FROM zaip_aios_activities WHERE payload_type
|
|
|
2316
2316
|
occurred_day_sp TEXT NOT NULL,
|
|
2317
2317
|
attributed_token_active_ms REAL NOT NULL,
|
|
2318
2318
|
PRIMARY KEY(activity_row_id, occurred_day_sp)
|
|
2319
|
-
);`),u.exec("CREATE INDEX IF NOT EXISTS zaip_activities_payload ON zaip_aios_activities(payload_type, activity_key)");let F=new ym(u),X=x=>b.get(x)?.contentHash??"",ne=(x,se)=>{if(!se.length)return;let D=Object.keys(se[0]),Ne=u.prepare(`INSERT INTO ${x}(${D.join(",")}) VALUES (${D.map(()=>"?").join(",")})`);for(let gt of se)Ne.run(...D.map(dn=>gt[dn]??null))};ne("canonical_run_index",P.filter(x=>!j.has(x.run_id)));let ve=new Set(k.filter(x=>j.has(x.run_id)).map(x=>x.agent_invocation_id));ne("invocation_usage_segments",U.filter(x=>!ve.has(x.agent_invocation_id))),ne("attributed_token_active_facts",$);for(let x of j)u.prepare("DELETE FROM zaip_aios_activities WHERE payload_type IS NULL AND run_id=?").run(x);for(let x of S)u.prepare("DELETE FROM zaip_aios_activities WHERE payload_type='parsed_source' AND source_path=?").run(x);let ge=u.prepare("INSERT INTO files(path, content, mtime_ms, size_bytes, content_sha256, artifact_kind, artifact_id, artifact_occurred_at, artifact_occurred_day_sp, artifact_task_id, artifact_change_id, artifact_run_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),q=u.prepare("INSERT INTO read_model_source_state(source_path, source_hash, mtime_ms, ctime_ms, size_bytes, file_identity, source_kind, last_processed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),A=0,I=0,he=32;for(let x=0;x<o.candidates.length;x+=he){let se=o.candidates.slice(x,x+he),D=await Promise.all(se.map(async gt=>{let dn=p.get(gt.source);if(dn?.content_sha256===gt.contentHash)return dn.content;let Ht=await(0,bm.readFile)(gt.path,"utf8");if((0,qL.createHash)("sha256").update(Ht).digest("hex")!==gt.contentHash)throw new Error(`Canonical source changed during refresh: ${gt.source}`);return Ht}));for(let gt=0;gt<se.length;gt+=1){let dn=se[gt],Ht=D[gt];if(dn===void 0||Ht===void 0)continue;let{source:_n,mtimeMs:hl,ctimeMs:je,size:An,fileIdentity:nt}=dn,xm=dn.contentHash,FM=_n.includes("/runs/")?"run":_n.includes("/artifacts/evidence/")?"evidence":_n.includes("/artifacts/validations/")||_n.includes("/artifacts/tests/")?"validation":_n.startsWith(".agents/config/")?"config":"entity",fo=F.read("artifact",_n,xm,()=>O$(_n,Ht));ge.run(_n,Ht,hl,An,xm,fo?.kind??null,fo?.id??null,fo?.occurredAt??null,fo?.occurredDaySp??null,fo?.taskId??null,fo?.changeId??null,fo?.runId??null),q.run(_n,xm,String(hl),String(je),An,nt,FM,new Date().toISOString()),A+=1}let Ne=52+Math.round((x+se.length)/o.candidates.length*20);i("source_import",Ne,`Lidas ${Math.min(x+se.length,o.candidates.length)} de ${o.candidates.length} fontes.`)}i("projection_build",74,"Organizando fatos e proje\xE7\xF5es do banco local.");let me=u.prepare("SELECT path, content FROM files WHERE (path LIKE '.agents/data/%' OR path LIKE '.agents/records/%') AND path NOT LIKE '.agents/data/runs/%' AND path NOT LIKE '.agents/records/runs/%' ORDER BY CASE WHEN path LIKE '.agents/data/%' THEN 1 ELSE 0 END, path").all(),Le=new Map(me.flatMap(x=>F.read("entities",x.path,X(x.path),()=>[...zb([x])])));for(let x of me)if(h.has(x.path)&&/^\.agents\/(?:data|records)\/specs\//.test(x.path))for(let[,se]of F.read("entities",x.path,X(x.path),()=>[...zb([x])]))se.creationRunId&&le.add(se.creationRunId);i("projection_entities",75,"Entidades can\xF4nicas interpretadas.");let Ce=u.prepare("INSERT INTO canonical_work_items(entity_kind, id, title, status, stage, risk, priority, spec_id, prd_id, change_id, creation_run_id, completed_run_id, occurred_at, occurred_day_sp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");for(let x of Le.values())x.kind!=="task"&&x.kind!=="spec"&&x.kind!=="prd"||x.occurredAt===null||Number.isNaN(Date.parse(x.occurredAt))||Ce.run(x.kind,x.id,x.title,x.status,x.stage,x.risk,x.priority,x.specId,x.prdId,x.changeId,x.creationRunId,x.completedRunId,x.occurredAt,bt(x.occurredAt));let Pe={executions:[],changes:[],decisions:[]};for(let x of me){if(!om(x.path))continue;let se=F.read("lifecycle",x.path,X(x.path),()=>w$([x]));Pe.executions.push(...se.executions),Pe.changes.push(...se.changes),Pe.decisions.push(...se.decisions)}Pe.executions=[...new Map(Pe.executions.map(x=>[x.id,x])).values()],Pe.changes=[...new Map(Pe.changes.map(x=>[x.id,x])).values()],Pe.decisions=[...new Map(Pe.decisions.map(x=>[x.id,x])).values()],i("projection_lifecycle",76,"Registros de ciclo de vida interpretados.");let rn=u.prepare("INSERT INTO canonical_executions(id, status, kind, origin_type, origin_id, created_at, occurred_day_sp, finished_at, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");for(let x of Pe.executions)rn.run(x.id,x.status,x.kind,x.originType,x.originId,x.createdAt,bt(x.createdAt),x.finishedAt,x.sourcePath);let Y=u.prepare("INSERT INTO canonical_changes(id, title, status, risk, source_type, source_id, source_spec_id, source_prd_id, requirement_ids_json, acceptance_ids_json, task_ids_json, result, created_at, occurred_day_sp, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");for(let x of Pe.changes)Y.run(x.id,x.title,x.status,x.risk,x.sourceType,x.sourceId,x.sourceSpecId,x.sourcePrdId,JSON.stringify(x.requirementIds),JSON.stringify(x.acceptanceIds),JSON.stringify(x.taskIds),x.result,x.createdAt,bt(x.createdAt),x.sourcePath);let ce=u.prepare("INSERT INTO canonical_decisions(id, title, origin, scope_type, scope_id, created_at, occurred_day_sp, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");for(let x of Pe.decisions)ce.run(x.id,x.title,x.origin,x.scopeType,x.scopeId,x.createdAt,bt(x.createdAt),x.sourcePath);i("projection_runs_started",77,"Construindo fatos das invoca\xE7\xF5es."),zL(Le,Pe.changes);let $e=u.prepare("UPDATE canonical_work_items SET stage=? WHERE entity_kind=? AND id=?");for(let x of Le.values())$e.run(x.stage,x.kind,x.id);let Xe=FL({database:u,previousActivities:k,parsedSources:F,refresh:a,hasPersistentSchema:m,dirtyRunIds:j,changedSources:h,oldIntervals:R,canonicalEntities:Le,entityChanged:J});i("projection_dimensions_started",78,"Construindo dimens\xF5es e agregados."),UL({...Xe,database:u,canonicalEntities:Le,changedCreationRunIds:le,hasPersistentSchema:m,files:A,skipped:I,fingerprint:s}),i("projection_overview_started",79,"Construindo a vis\xE3o geral."),tS(e,u),u.exec("COMMIT;"),i("projection_finalize",80,"Finalizando \xEDndices do banco persistente do dashboard."),d=A}catch(p){throw u.exec("ROLLBACK;"),p}u.exec("PRAGMA busy_timeout=0; PRAGMA wal_checkpoint(TRUNCATE);")}finally{u.close()}let _=r+l;return i("snapshot_ready",86,"O banco SQLite persistente est\xE1 pronto."),na(n),{files:d,path:n,cache:"rebuilt",fingerprint_ms:l,materialize_ms:Math.round(performance.now()-_),refresh:a}}async function po(e,t,n,i={}){let r=e instanceof ct?KQ(e,t,n,i):await nl(e,t,n,i);if(!(e instanceof ct))return r;let o=e.firstFoldMonthlyQuick(n),a=n.from===null&&n.to===null?e.firstFoldViewportAllTime().aggregate:o?.aggregate??e.firstFoldAggregate(n);return{...r,summary:{...r.summary,projection_updated_at:e.projectionUpdatedAt(),latest_token_collected_at:e.latestTokenCollectedAt(),run_count:a.total_run_count,overview_metrics:{...r.summary.overview_metrics,duration_ms:a.duration_ms,tokens:a.total_tokens,cost_brl:a.cost_brl,execution_day_count:a.execution_day_count,data_source:"run_records"}}}}function KQ(e,t,n,i){let r=e.firstFoldMonthlyQuick(n),o=n.from===null&&n.to===null&&i.includeExtended===!0?e.firstFoldAllTime():null,a=o??(n.from===null&&n.to===null?e.firstFoldViewportAllTime():null),s=n.from===null&&n.to===null&&i.includeBoardTasks===!0?e.firstFoldBoardAllTime():null,l=j=>r?.pages[j]??s?.pages[j]??e.canonicalWorkPage(j,n,0,1e4).rows,c=a===null||i.includeBoardTasks===!0,u=c?l("task"):[],d=c?l("spec"):[],_=c?l("prd"):[],p=a?.aggregate??r?.aggregate??e.firstFoldAggregate(n),g=a?.task_status_counts.draft??0,m=a===null?u.length:Math.max(0,a.aggregate.task_count-g),f=n.from===null&&n.to===null&&(o!==null||i.includeTopTasks===!0)?o?.top_tasks??e.firstFoldTopTasksAllTime():null,v=f===null?(r?.top_tasks??e.topTasks(n)).map(j=>({task_id:j.task_id,duration_ms:j.duration_ms,total_tokens:j.total_tokens,cost_brl:j.cost_brl,run_count:j.run_count})):Qp(f),S=a===null?null:o?.macro_metrics??e.firstFoldMacroMetrics(),b=S===null?{specs:Pb(d,"spec"),prds:Pb(_,"prd")}:Object.fromEntries(["specs","prds"].map(j=>{let Q=S[j];return[j,{status_counts:Q.status_counts,classification_counts:Q.classification_counts,entity_count:Q.entity_count,total_run_count:Q.total_run_count,total_duration_ms:Q.total_duration_ms,total_tokens:Q.total_tokens,total_cost_usd:Q.total_cost_usd,total_cost_brl:Q.total_cost_brl,average_duration_ms:Q.average_duration_ms,average_tokens:Q.average_tokens,average_cost_usd:Q.average_cost_usd,average_cost_brl:Q.average_cost_brl,latest_created_at:Q.latest_created_at,top_entities:Q.top_entities.map(C=>({entity_id:C.entity_id,title:C.title,duration_ms:C.total_duration_ms,total_tokens:C.total_tokens,total_cost_usd:C.total_cost_usd,cost_brl:C.total_cost_brl,run_count:C.total_run_count,duration_share:C.duration_share}))}]})),h=Object.fromEntries(Object.entries(a?.task_status_counts??{}).filter(([j])=>j!=="draft")),k=a?.task_risk_counts??{};if(a===null)for(let j of u){let Q=typeof j.status=="string"?j.status:"draft",C=typeof j.risk=="string"?j.risk:"standard";h[Q]=(h[Q]??0)+1,k[C]=(k[C]??0)+1}let P=a?.aggregate.latest_task_created_at??[...u,...d,..._].map(j=>typeof j.occurred_at=="string"?j.occurred_at:null).filter(j=>j!==null).sort().at(-1)??null,U={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}},$={...U,tokens:{...U.tokens,total:p.total_tokens},cost:{...U.cost,brl:p.cost_brl}},B={conversation:U,planning:U,execution:U,total:$,new_work:U,rework:U},z=i.includePeriods===!0?e.dailyPeriods(n):{},R=Object.values(z).some(j=>j.usage.total_tokens.unknown>0||j.usage.cost.unknown>0),L=e.canonicalSource(),J=j=>({schema_version:2,id:String(j.id),revision:1,change_id:typeof j.change_id=="string"?j.change_id:"",title:String(j.title??j.id),short_name:String(j.title??j.id),objective:"",status:XQ(j.status),attempt_count:null,risk:YQ(j.risk),priority:"medium",owner:null,requirement_ids:[],acceptance_ids:[],depends_on:[],write_scopes:[],created_at:String(j.occurred_at),updated_at:String(j.occurred_at),started_at:null,finished_at:null,result:null,artifact_path:L,progress:0,spec_id:typeof j.spec_id=="string"?j.spec_id:null,origin:typeof j.origin=="string"?j.origin:null,execution_started:!1,telemetry:{duration_ms:ci(j.total_duration),tokens:ci(j.total_tokens),cost_brl:ci(j.total_cost_brl)}}),le=(j,Q)=>{let C={...U,tokens:{...U.tokens,total:ci(j.total_tokens)},cost:{...U.cost,brl:ci(j.total_cost_brl)}};return{id:String(j.id),title:String(j.title??j.id),created_at:String(j.occurred_at),updated_at:String(j.occurred_at),kind:Q,parent_id:Q==="spec"&&typeof j.prd_id=="string"?j.prd_id:null,artifact_path:L,lifecycle_status:String(j.status??"draft"),work_status:QQ(j.stage??j.status),execution_ids:[],task_ids:typeof j.task_ids_json=="string"?JSON.parse(j.task_ids_json):[],planned_tasks:[],canonical_run_ids:[],run_ids:[],root_execution_run_ids:[],execution_count:0,task_count:ci(j.task_count)??0,run_count:ci(j.invocation_count)??0,duration_ms:ci(j.total_duration),decisions:{human:0,agent:0},rework_run_count:ci(j.rework_run_count)??0,quality:{completed_tasks:ci(j.completed_task_count)??0,task_completion_rate:Number(j.task_count)>0?Number(j.completed_task_count??0)/Number(j.task_count):0,terminal_runs:0,successful_runs:0,terminal_success_rate:0,rework_rate:0},usage:{conversation:U,planning:U,execution:U,total:C,new_work:U,rework:U}}};return{schema_version:2,layout_version:t.version,readonly:!0,source:L,filters:n,summary:{prd_count:a?.aggregate.prd_count??_.length,spec_count:a?.aggregate.spec_count??d.length,execution_count:0,task_count:m,run_count:p.total_run_count,overview_metrics:{duration_ms:p.duration_ms,execution_day_count:p.execution_day_count,tokens:p.total_tokens,cost_brl:p.cost_brl,prd_count:a?.aggregate.prd_count??_.length,spec_count:a?.aggregate.spec_count??d.length,selected_counts:{prds:a?.aggregate.prd_count??_.length,specs:a?.aggregate.spec_count??d.length},task_count:m,completed_prd_count:a?.aggregate.completed_prd_count??b.prds.status_counts.completed??0,completed_spec_count:a?.aggregate.completed_spec_count??b.specs.status_counts.completed??0,completed_task_count:a?.aggregate.completed_task_count??h.completed??0,task_status_counts:h,task_risk_counts:k,top_tasks:v,...b===void 0?{}:{macro_metrics:b},latest_task_created_at:P,coverage:{duration:1,tokens:R?0:1,cost:R?0:1},data_source:"run_records",partial:!0},decisions:{human:0,agent:0},source_latest_at:P,quality:{completed_tasks:h.completed??0,task_completion_rate:m===0?0:(a?.aggregate.completed_task_count??h.completed??0)/m,terminal_runs:0,successful_runs:0,terminal_success_rate:0,rework_rate:0},reconciliation:{phase_tokens_match_total:!0,phase_usd_match_total:!0,phase_brl_match_total:!0,origin_tokens_match_total:!0},usage:B,periods:{daily:i.includePeriods===!0?z:{}}},origins:{conversation:B,task:B,spec:B,prd:B},prds:_.map(j=>le(j,"prd")),specs:d.map(j=>le(j,"spec")),tasks:i.includeBoardTasks?u.map(J):[],changes:[],executions:[],runs:[],decisions:[],evidences:[],validations:[]}}function ci(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function XQ(e){return["draft","planned","executing","verifying","completed","failed","blocked","cancelled"].includes(String(e))?String(e):"draft"}function YQ(e){return["lite","standard","critical"].includes(String(e))?String(e):"standard"}function QQ(e){let t=String(e);return["executing","verifying","completed","blocked","failed","cancelled"].includes(t)?t:"planning"}async function sS(e,t={from:null,to:null}){if(e instanceof ct)return e.costMonitorSummaryAggregate(t);let n=await new Bt(e).readDailyReadModels("overview");if(n===null)throw new Error("Lifecycle daily overview is not initialized");return{periods:{daily:Object.fromEntries(Object.entries(n.days).map(([i,r])=>[i,r.overview]))}}}async function WL(e,t,n,i){let r=i??await Ai(e),{from:o,to:a}=Et(n),s=Jn(n),l=e instanceof ct?await po(e,r,{from:o,to:a}):await as(e,r,{from:o,to:a}),c=e instanceof ct?Gp(await sS(e,{from:o,to:a}),l,s,s==="BRL"?(await al(e))?.rate??null:null):await os(e,l,s);return{operations:l,costs:c,dashboard:await tm(e,t),projection:{source_latest_at:l.summary.source_latest_at,updated_at:l.summary.projection_updated_at??null,latest_token_collected_at:l.summary.latest_token_collected_at??null,served_at:new Date().toISOString()}}}function BL(e,t){let{filesystem:n,canonicalFilesystem:i,isSqliteSnapshot:r,readLayout:o,readSnapshot:a,readAggregate:s,clearSnapshotCache:l}=t;e.on(["GET","HEAD"],`${Se}/cost-monitor`,async c=>{try{let u=c.req.query("scope")??"summary";if(u==="summary"){let m=await o(),{from:f,to:v}=Et(c),S=Jn(c),b=performance.now(),[h,k]=await Promise.all([sS(n,{query:c.req.query("query")??"",from:f,to:v,providers:tt(c,"provider"),models:tt(c,"model"),agents:tt(c,"agent"),phases:tt(c,"phase"),statuses:tt(c,"status"),tasks:tt(c,"task"),specs:tt(c,"spec"),prds:tt(c,"prd"),executions:tt(c,"execution"),changes:tt(c,"change"),priorities:tt(c,"priority"),risks:tt(c,"risk"),origins:tt(c,"origin"),workTypes:[...new Set([...tt(c,"workType"),...tt(c,"work_type")])]}),S==="BRL"?al(n):Promise.resolve(null)]),P=performance.now()-b,U={schema_version:1,layout_version:m.version,readonly:!0,source:".agents/records",filters:{from:f,to:v},summary:{task_count:h.task_count??0},prds:[],specs:[],runs:[]},$=performance.now(),B=Gp(h,U,S,k?.rate??null);return c.header("Server-Timing",`cost_sql;dur=${P.toFixed(1)},cost_projection;dur=${(performance.now()-$).toFixed(1)}`),ye(c,B,200,!0)}if(u==="runs"){let m=await o(),{from:f,to:v}=Et(c),S=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),b=Math.min(500,Math.max(1,Number.parseInt(c.req.query("limit")??"100",10)||100));return ye(c,await c$(r?i:n,m,c,{from:f,to:v},S,b),200,!0)}if(Ib(c))return ye(c,(await a(c)).costs);let d=await o(),{from:_,to:p}=Et(c),g=await as(n,d,{from:_,to:p});return ye(c,await a$(n,g,c))}catch(u){if(u instanceof Dt)throw u;return ye(c,{error:u instanceof Error?u.message:String(u)},400)}}),e.on(["GET","HEAD"],`${Se}/developers`,async c=>{if(!(n instanceof ct))return ye(c,{error:"Developer attribution requires the SQLite read model"},409);let{from:u,to:d}=Et(c);return ye(c,n.developerCostAggregate({from:u,to:d,accountIds:tt(c,"account_id")}),200,!0)}),e.on(["GET","HEAD"],`${Se}/operations/developers`,async c=>{if(!(n instanceof ct))return ye(c,{error:"Developer attribution requires the SQLite read model"},409);let{from:u,to:d}=Et(c);return ye(c,n.operationsDeveloperAggregate({from:u,to:d,accountIds:tt(c,"account_id")}),200,!0)})}ea();ri();function ZL(e){return{query:(e.req.query("query")??"").trim().toLocaleLowerCase(),status:e.req.query("status")??"",risk:e.req.query("risk")??"",origin:e.req.query("origin")??"",kind:e.req.query("kind")??""}}function HL(e){if(e===void 0||!["definition","planning","ready","executing","verifying","completed","blocked","cancelled","failed"].includes(e))throw new Error("A valid Kanban stage is required");return e}function JL(e,t,n,i,r,o){let a=new Map(e.changes.map(b=>[b.id,b.source.type])),s=b=>{let h=b.origin;return a.get(b.change_id)??(typeof h=="string"?h:b.spec_id===null?"task":"spec")},l=b=>o.query===""||b.some(h=>h?.toLocaleLowerCase().includes(o.query)),c=b=>(o.status===""||ss(b)===o.status)&&(o.risk===""||b.risk===o.risk)&&(o.origin===""||s(b)===o.origin)&&l([b.id,b.title,b.short_name,b.objective,b.change_id,b.spec_id]),u=b=>o.risk===""&&o.origin===""&&(o.status===""||im(b,e.tasks)===o.status)&&l([b.id,b.title,b.parent_id]),d=e.tasks.filter(c),_=e.prds.filter(u),p=e.specs.filter(u),m=[..._.map(b=>({kind:"prd",row:b})),...p.map(b=>({kind:"spec",row:b})),...d.map(b=>({kind:"task",row:b}))].filter(b=>(b.kind==="task"?ss(b.row):im(b.row,e.tasks))===t).toSorted((b,h)=>{let k=new Map(r.map((P,U)=>[P,U]));return(k.get(b.row.id)??Number.MAX_SAFE_INTEGER)-(k.get(h.row.id)??Number.MAX_SAFE_INTEGER)||String(h.row.updated_at??"").localeCompare(String(b.row.updated_at??""))||b.row.id.localeCompare(h.row.id)}).filter(b=>(b.kind==="task"?ss(b.row):im(b.row,e.tasks))===t),f=o.kind===""?m:o.kind==="all-tasks"?m.filter(b=>b.kind==="task"):o.kind==="standalone-task"?m.filter(b=>b.kind==="task"&&b.row.spec_id===null):o.kind==="task"?m.filter(b=>b.kind==="task"&&b.row.spec_id!==null):m.filter(b=>b.kind===o.kind),v=f.slice(n,n+i),S=new Set(v.map(b=>b.row.id));return{stage:t,offset:n,total:f.length,totals_by_kind:{all:m.length,task:m.filter(b=>b.kind==="task"&&b.row.spec_id!==null).length,"standalone-task":m.filter(b=>b.kind==="task"&&b.row.spec_id===null).length,prd:m.filter(b=>b.kind==="prd").length,spec:m.filter(b=>b.kind==="spec").length},prds:v.filter(b=>b.kind==="prd").map(b=>b.row),specs:v.filter(b=>b.kind==="spec").map(b=>b.row),tasks:v.filter(b=>b.kind==="task").map(b=>b.row),changes:e.changes.filter(b=>b.task_ids.some(h=>S.has(h)))}}function GL(e,t,n,i,r){let o=c=>c.rework_run_count>0?"rework":c.task_count>0?"structured":"empty",s=(t==="task"?e.tasks.filter(c=>c.risk===n):(t==="spec"?e.specs:e.prds).filter(c=>o(c)===n)).toSorted((c,u)=>String(u.updated_at??u.created_at??"").localeCompare(String(c.updated_at??c.created_at??""))||c.id.localeCompare(u.id)),l=s.slice(i,i+r);return{offset:i,total:s.length,prds:t==="prd"?l:[],specs:t==="spec"?l:[],tasks:t==="task"?l:[],changes:t==="task"?e.changes.filter(c=>l.some(u=>c.task_ids.includes(u.id))):[]}}ri();ri();function Sm(e,t,n,i,r,o,a=null){let s=Object.entries(e.days).sort(([S],[b])=>b.localeCompare(S)),l=n.from===null?null:KL(n.from),c=n.to===null?null:KL(n.to),u=s.filter(([S])=>(l===null||S>=l)&&(c===null||S<=c)),_=(t==="overview"?u.map(([S,b])=>({day:S,...b.overview})):e8(t,XL(u.flatMap(([,S])=>S[t])),XL(s.flatMap(([,S])=>S[t])),n)).filter(S=>r8(S,i)),p=n8(a),g=p===null?_:_.filter(S=>`${YL(S)}\0${QL(S)}`<p),m=p===null?r:0,f=g.slice(m,m+o),v=f.at(-1);return{data_source:"lifecycle_daily_read_models",snapshot_id:e.updated_at,source_latest_at:e.source_latest_at,kind:t,offset:m,limit:o,total:_.length,has_more:m+o<g.length,next_cursor:v===void 0||m+o>=g.length?null:t8(YL(v),QL(v)),rows:f}}function KL(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)?e:nn(e,"day")}function e8(e,t,n,i){if(e!=="tasks"&&e!=="specs"&&e!=="prds")return[...t];let r=new Set(["completed","delivered","failed","cancelled","superseded","rolled_back"]),o=new Map(n.map(c=>[c.id,c])),a=t.filter(c=>{let u=o.get(c.id)??c;if(u.status===null||!r.has(u.status)||c.run_count>0)return!0;let d=u.window_at??u.occurred_at;return(i.from===null||d>=i.from)&&(i.to===null||d<=i.to)}),s=new Set(a.map(c=>c.id)),l=()=>({known_sum:0,unknown:0,complete:!0,coverage_ratio:1});return[...a,...n.filter(c=>!s.has(c.id)&&(c.status===null||!r.has(c.status))).map(c=>({...c,run_count:0,cost_currency:null,metrics:{duration:l(),total_tokens:l(),cost:l()}}))].sort((c,u)=>u.occurred_at.localeCompare(c.occurred_at)||c.id.localeCompare(u.id))}function XL(e){let t=new Map;for(let n of e){let i=t.get(n.id);if(i===void 0){t.set(n.id,structuredClone(n));continue}let r=i.run_count;if(n.run_count>0){let o=n.lifecycle_elapsed_ms??null;if(r===0)i.lifecycle_elapsed_ms=o;else{let a=i.lifecycle_elapsed_ms??null;i.lifecycle_elapsed_ms=a===null||o===null?null:a+o}}i.run_count+=n.run_count;for(let o of["duration","total_tokens","cost"]){let a=i.metrics[o],s=n.metrics[o];a.known_sum+=s.known_sum,a.unknown+=s.unknown,a.complete=a.unknown===0;let l=i.run_count;a.coverage_ratio=l===0?1:Math.max(0,Math.min(1,(l-a.unknown)/l))}}return[...t.values()].sort((n,i)=>i.occurred_at.localeCompare(n.occurred_at)||n.id.localeCompare(i.id))}function YL(e){let t=e;return typeof t.occurred_at=="string"?t.occurred_at:typeof t.day=="string"?t.day:""}function QL(e){let t=e;return typeof t.id=="string"?t.id:typeof t.day=="string"?t.day:""}function t8(e,t){return encodeURIComponent(JSON.stringify([e,t]))}function n8(e){if(e===null)return null;try{let t=JSON.parse(decodeURIComponent(e));return Array.isArray(t)&&typeof t[0]=="string"&&typeof t[1]=="string"?`${t[0]}\0${t[1]}`:null}catch{return null}}function r8(e,t){return t.status&&e.status!==t.status||t.risk&&e.risk!==t.risk?!1:t.query?Object.values(e).some(n=>typeof n=="string"&&n.toLocaleLowerCase().includes(t.query)):!0}var eM=require("node:path");function mo(e){return{query:(e.req.query("query")??"").trim().toLocaleLowerCase(),status:(e.req.query("status")??"").trim(),risk:(e.req.query("risk")??"").trim()}}function cS(e,t){return e.filter(n=>t.status&&n.status!==t.status?!1:t.query?[n.id,n.task_id,n.execution_id,n.conversation_id,n.parent_run_id,n.run_kind,n.phase,n.agent].some(i=>typeof i=="string"&&i.toLocaleLowerCase().includes(t.query)):!0)}function lS(e,t){return e.filter(n=>t.status&&n.status!==t.status||t.risk&&n.risk!==t.risk?!1:t.query?[n.id,n.title,n.status,n.risk,n.source,n.origin,n.scope_type,n.scope_id].flatMap(i=>typeof i=="object"&&i!==null?Object.values(i):[i]).some(i=>typeof i=="string"&&i.toLocaleLowerCase().includes(t.query)):!0)}function tM(e,t){if(t!=="executions"&&t!=="conversations")return[...e];let n=new Map;for(let i of e){let r=t==="executions"?i.execution_id:i.conversation_id;if(r==null)continue;let o=n.get(r)??{...i,id:r,duration_ms:null,total_tokens:null,cost:null};i.phase==="execution"&&i.parent_run_id===null&&i.duration_ms!==null&&(o.duration_ms=(o.duration_ms??0)+i.duration_ms),i.total_tokens!==null&&(o.total_tokens=(o.total_tokens??0)+i.total_tokens),i.cost!==null&&(o.cost=(o.cost??0)+i.cost);let a=o.finished_at??o.started_at;(i.finished_at??i.started_at)>a&&(o.status=i.status),i.started_at<o.started_at&&(o.started_at=i.started_at),(o.finished_at===null||i.finished_at!==null&&i.finished_at>o.finished_at)&&(o.finished_at=i.finished_at),n.set(r,o)}return[...n.values()].sort((i,r)=>r.started_at.localeCompare(i.started_at))}function nM(e,t,n,i=[]){let r=new Map;if(n==="conversations")for(let a of i)r.set(a.id,a.status);let o=new Map;for(let a of t){let s=a.data?.origin!==null&&typeof a.data?.origin=="object"?a.data.origin.conversation_id:null,l=n==="executions"?a.id:typeof s=="string"?s:null;l===null||r.has(l)||(n==="executions"?r.set(l,a.status):o.has(l)?o.set(l,null):o.set(l,a.status))}for(let[a,s]of o)r.set(a,s);return e.map(a=>{let s=n==="executions"?a.execution_id:a.conversation_id;return s==null||!r.has(s)?a:{...a,status:r.get(s)??null}})}function rM(e,t,n,i){return e.flatMap(r=>{let o=r.data,a=typeof o?.created_at=="string"?o.created_at:null;if(a===null||n!==null&&a<n||i!==null&&a>i)return[];let s=o?.source;if(s===null||typeof s!="object"||!("type"in s))return[];let l=s;return l.type==="task"&&typeof l.task_id=="string"||l.type==="spec"&&typeof l.spec_id=="string"||l.type==="prd"&&typeof l.prd_id=="string"?[{id:r.id,title:r.title??(typeof o?.title=="string"?o.title:r.id),created_at:a,status:r.status??(typeof o?.status=="string"?o.status:"unclassified"),risk:r.risk??(typeof o?.risk=="string"?o.risk:"unclassified"),source:l,requirement_ids:uS(o?.requirement_ids),acceptance_ids:uS(o?.acceptance_ids),task_ids:uS(o?.task_ids),result:typeof o?.result=="string"?o.result:null,artifact_path:t.activePath("change",r.id)}]:[]}).sort((r,o)=>o.created_at.localeCompare(r.created_at))}function iM(e,t,n,i){return e.flatMap(r=>{let o=r.data,a=typeof o?.created_at=="string"?o.created_at:null;return a===null||n!==null&&a<n||i!==null&&a>i||o?.origin!=="human"&&o?.origin!=="agent"||o?.scope_type!=="change"&&o?.scope_type!=="execution"||typeof o?.scope_id!="string"?[]:[{id:r.id,title:r.title??(typeof o?.title=="string"?o.title:r.id),origin:o.origin,scope_type:o.scope_type,scope_id:o.scope_id,artifact_path:`${eM.posix.dirname(t.activePath(o.scope_type,o.scope_id))}/decisions/${r.id}.md`,created_at:a}]}).sort((r,o)=>o.created_at.localeCompare(r.created_at))}function uS(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function oM(e,t,n,i){e.on(["GET","HEAD"],"/api/v2/operations/read-models",async r=>{let o=r.req.query("kind");if(!["overview","tasks","specs","prds","executions","conversations"].includes(o))return i(r,{error:"Unsupported daily read model"},400,!1);let a=Math.max(0,Number.parseInt(r.req.query("offset")??"0",10)||0),s=Math.min(200,Math.max(1,Number.parseInt(r.req.query("limit")??"20",10)||20)),{from:l,to:c}=Et(r),u=mo(r),d=await n(`operations:read-model:${o}:${l??""}:${c??""}:${a}:${s}:${r.req.query("cursor")??""}:${u.query}:${u.status}:${u.risk}`,async()=>{let _=await new Bt(t).readDailyReadModels(o);return _===null?{data_source:"lifecycle_daily_read_models",snapshot_id:null,source_latest_at:null,kind:o,offset:a,limit:s,total:0,has_more:!1,next_cursor:null,rows:[]}:Sm(_,o,{from:l,to:c},u,a,s,r.req.query("cursor")??null)});return i(r,d,200,!0)})}ri();function aM(e,t,n,i){e.on(["GET","HEAD"],"/api/v2/operations/runs",async r=>{let o=Math.max(0,Number.parseInt(r.req.query("offset")??"0",10)||0),a=Math.min(200,Math.max(1,Number.parseInt(r.req.query("limit")??"100",10)||100)),{from:s,to:l}=Et(r),c=r.req.query("kind")??"runs";if(c!=="runs"&&c!=="executions"&&c!=="conversations")return i(r,{error:"Unsupported Operations Run page"},400,!1);let u=c,d=mo(r),_=await n(`operations:runs:${u}:${s??""}:${l??""}:${o}:${a}:${d.query}:${d.status}:${d.risk}`,async()=>{if(u==="executions"||u==="conversations"){let h=await new Bt(t).readDailyReadModels(u);if(h!==null){let k=Sm(h,u,{from:s,to:l},d,o,a);return i8(u,k,k.rows)}}let p=new Bt(t),[g,m]=await Promise.all([t.readText(".agents/records/lifecycle/summary.json"),p.readEntities("execution")]),v=(JSON.parse(g).run_metrics??[]).filter(h=>(s===null||h.started_at>=s)&&(l===null||h.started_at<=l)&&(u==="runs"||u==="conversations"&&h.phase==="conversation"&&h.conversation_id!==null||u==="executions"&&h.execution_id!==null)),S=tM(v,u),b=cS(u==="runs"?S:nM(S,m,u),d);return{data_source:"lifecycle_manifest_summary",kind:u,offset:o,limit:a,total:b.length,rows:b.slice(o,o+a)}});return i(r,_,200,!0)})}function i8(e,t,n){let i=r=>r.complete||r.known_sum>0?r.known_sum:null;return{data_source:t.data_source,kind:e,offset:t.offset,limit:t.limit,total:t.total,rows:n.map(r=>({id:r.id,started_at:r.occurred_at,finished_at:null,task_id:r.kind==="execution"?r.parent_id:null,execution_id:r.kind==="execution"?r.id:r.parent_id,conversation_id:r.kind==="conversation"?r.id:null,parent_run_id:null,run_kind:"run",phase:r.kind,status:r.status,duration_ms:i(r.metrics.duration),lifecycle_elapsed_ms:r.lifecycle_elapsed_ms??null,total_tokens:i(r.metrics.total_tokens),cost:i(r.metrics.cost),currency:r.cost_currency}))}}function sM(e,t){let{filesystem:n,canonicalFilesystem:i,isSqliteSnapshot:r,readLayout:o,readSnapshot:a,readAggregate:s,clearSnapshotCache:l}=t;e.on(["GET","HEAD"],`${Se}/operations`,async c=>{try{let u=performance.now(),d=c.req.query("scope");if(d!=="overview"&&d!=="quick"&&d!=="detail"&&d!=="board"&&d!=="traceability"&&d!=="classification")return ye(c,(await a(c)).operations);let _=await o(),p=performance.now()-u,{from:g,to:m}=Et(c);if(d==="board"||d==="traceability"){let v=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),S=Math.min(50,Math.max(1,Number.parseInt(c.req.query("limit")??"10",10)||10)),b=await s(`operations:board:${g??""}:${m??""}`,async()=>{let $=await po(n,_,{from:g,to:m},{includeBoardTasks:!0});return{projection:$,priority:await Xp(i,Yp($))}});if(d==="traceability"){let $=b.projection.tasks.toSorted((B,z)=>z.created_at.localeCompare(B.created_at)||z.id.localeCompare(B.id));return ye(c,{tasks:$.slice(v,v+S),total:$.length,offset:v,limit:S},200,!0)}let h=HL(c.req.query("stage")),k=ZL(c),P=JSON.stringify({from:g,to:m,stage:h,offset:v,limit:S,...k}),U=await s(`operations:board-page:${P}`,async()=>JL(b.projection,h,v,S,b.priority.item_ids,k));return ye(c,U,200,!0)}if(d==="classification"){let v=c.req.query("kind"),S=c.req.query("classification");if(v!=="task"&&v!=="spec"&&v!=="prd")return ye(c,{error:"A valid work kind is required"},400);if(!["lite","standard","critical","empty","structured","rework"].includes(S??""))return ye(c,{error:"A valid classification is required"},400);let b=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),h=Math.min(50,Math.max(1,Number.parseInt(c.req.query("limit")??"50",10)||50)),k=await s(`operations:classification:${g??""}:${m??""}`,()=>po(n,_,{from:g,to:m},{includeBoardTasks:!0}));return ye(c,GL(k,v,S,b,h),200,!0)}if(d==="quick"){let v=performance.now(),S=await s(`operations:quick:${g??""}:${m??""}`,()=>po(n,_,{from:g,to:m},{includeTopTasks:g===null&&m===null,includeExtended:g===null&&m===null}),c.req.query("fresh")==="1");if(process.env.ZAIP_DASHBOARD_PROFILE_FIRST_FOLD==="1"&&n instanceof ct){let b=n.firstFoldViewportProfile();c.header("Server-Timing",[`layout;dur=${Math.round(p*10)/10}`,`projection;dur=${Math.round((performance.now()-v)*10)/10}`,...Object.entries(b).map(([h,k])=>`${h};dur=${k}`)].join(", "))}return ye(c,S,200,!0)}let f=n instanceof ct?await po(n,_,{from:g,to:m},{includeBoardTasks:d==="detail",includeExtended:d==="detail"||d==="overview",includePeriods:d==="detail"||d==="overview"}):await as(n,_,{from:g,to:m},d==="overview");return ye(c,f,200,d==="overview")}catch(u){if(u instanceof Dt)throw u;return ye(c,{error:u instanceof Error?u.message:String(u)},400)}}),aM(e,r?i:n,s,ye),e.on(["GET","HEAD"],`${Se}/sqlite-read-models`,async c=>{if(!(n instanceof ct))return ye(c,{error:"SQLite read model is not active"},409);let u=c.req.query("kind"),d=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),_=Math.min(200,Math.max(1,Number.parseInt(c.req.query("limit")??"20",10)||20));if(u==="overview"){let f=c.req.query("period");return f!=="day"&&f!=="month"&&f!=="year"?ye(c,{error:"Unsupported SQLite overview period"},400):ye(c,n.overviewPage(f,d,_),200,!0)}if(u!=="task"&&u!=="spec"&&u!=="prd")return ye(c,{error:"Unsupported SQLite read model"},400);let{from:p,to:g}=Et(c),m=mo(c);return ye(c,n.summaryPage(u,{from:p,to:g,...m},d,_,c.req.query("cursor")??null),200,!0)}),e.on(["GET","HEAD"],`${Se}/sqlite-views`,async c=>{if(!(n instanceof ct))return ye(c,{error:"SQLite read model is not active"},409);let u=c.req.query("view");if(u===void 0||!Object.hasOwn(ra,u))return ye(c,{error:"Unsupported SQLite view"},400);let d=Number.parseInt(c.req.query("limit")??"",10),_=u.includes("agent_invocations")?100:u==="first_fold_top_tasks"?5:50,p=Math.min(200,Math.max(1,Number.isFinite(d)?d:_)),{from:g,to:m}=Et(c),f=S=>{let b=c.req.query(S);return b===void 0?{}:{[S]:b}},v=c.req.query("kind");return u==="operations_work_list"&&v!==void 0&&!["all","task","standalone-task","prd","spec"].includes(v)?ye(c,{error:"Unsupported Operations work-list kind"},400):ye(c,n.viewPage(u,{from:g,to:m,...f("query"),...f("status"),...f("risk"),...f("provider"),...f("model"),...f("agent"),...f("phase"),...f("origin"),...f("workType"),...f("priority"),...v===void 0?{}:{kind:v},offset:Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),limit:p}),200,!0)}),e.on(["GET","HEAD"],`${Se}/work-priority`,async c=>{let u=await Ai(i),d=await il(i,u,{from:null,to:null});return ye(c,await Xp(i,Yp(d)))}),e.on(["GET","HEAD"],`${Se}/operations/entities`,async c=>{let u=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),d=Math.min(500,Math.max(1,Number.parseInt(c.req.query("limit")??"100",10)||100)),_=c.req.query("kind");if(_!=="changes"&&_!=="decisions")return ye(c,{error:"Unsupported Operations entity page"},400);let{from:p,to:g}=Et(c),m=mo(c),f=await s(`operations:entities:${_}:${p??""}:${g??""}:${u}:${d}:${m.query}:${m.status}:${m.risk}`,async()=>{let v=await o(),S=await new Bt(n).readEntities(_==="changes"?"change":"decision"),b=_==="changes"?rM(S,v,p,g):iM(S,v,p,g),h=lS(b,m);return{data_source:"lifecycle_manifest_shards",kind:_,offset:u,limit:d,total:h.length,rows:h.slice(u,u+d)}});return ye(c,f,200,!0)}),oM(e,n,s,ye),e.put(`${Se}/work-priority`,async c=>{let u=Nb(await c.req.json());return await i.writeTextAtomic(cC,`${JSON.stringify(u,null,2)}
|
|
2319
|
+
);`),u.exec("CREATE INDEX IF NOT EXISTS zaip_activities_payload ON zaip_aios_activities(payload_type, activity_key)");let F=new ym(u),X=x=>b.get(x)?.contentHash??"",ne=(x,se)=>{if(!se.length)return;let D=Object.keys(se[0]),Ne=u.prepare(`INSERT INTO ${x}(${D.join(",")}) VALUES (${D.map(()=>"?").join(",")})`);for(let gt of se)Ne.run(...D.map(dn=>gt[dn]??null))};ne("canonical_run_index",P.filter(x=>!j.has(x.run_id)));let ve=new Set(k.filter(x=>j.has(x.run_id)).map(x=>x.agent_invocation_id));ne("invocation_usage_segments",U.filter(x=>!ve.has(x.agent_invocation_id))),ne("attributed_token_active_facts",$);for(let x of j)u.prepare("DELETE FROM zaip_aios_activities WHERE payload_type IS NULL AND run_id=?").run(x);for(let x of S)u.prepare("DELETE FROM zaip_aios_activities WHERE payload_type='parsed_source' AND source_path=?").run(x);let ge=u.prepare("INSERT INTO files(path, content, mtime_ms, size_bytes, content_sha256, artifact_kind, artifact_id, artifact_occurred_at, artifact_occurred_day_sp, artifact_task_id, artifact_change_id, artifact_run_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),q=u.prepare("INSERT INTO read_model_source_state(source_path, source_hash, mtime_ms, ctime_ms, size_bytes, file_identity, source_kind, last_processed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),A=0,I=0,he=32;for(let x=0;x<o.candidates.length;x+=he){let se=o.candidates.slice(x,x+he),D=await Promise.all(se.map(async gt=>{let dn=p.get(gt.source);if(dn?.content_sha256===gt.contentHash)return dn.content;let Ht=await(0,bm.readFile)(gt.path,"utf8");if((0,qL.createHash)("sha256").update(Ht).digest("hex")!==gt.contentHash)throw new Error(`Canonical source changed during refresh: ${gt.source}`);return Ht}));for(let gt=0;gt<se.length;gt+=1){let dn=se[gt],Ht=D[gt];if(dn===void 0||Ht===void 0)continue;let{source:_n,mtimeMs:hl,ctimeMs:je,size:An,fileIdentity:nt}=dn,xm=dn.contentHash,FM=_n.includes("/runs/")?"run":_n.includes("/artifacts/evidence/")?"evidence":_n.includes("/artifacts/validations/")||_n.includes("/artifacts/tests/")?"validation":_n.startsWith(".agents/config/")?"config":"entity",fo=F.read("artifact",_n,xm,()=>O$(_n,Ht));ge.run(_n,Ht,hl,An,xm,fo?.kind??null,fo?.id??null,fo?.occurredAt??null,fo?.occurredDaySp??null,fo?.taskId??null,fo?.changeId??null,fo?.runId??null),q.run(_n,xm,String(hl),String(je),An,nt,FM,new Date().toISOString()),A+=1}let Ne=52+Math.round((x+se.length)/o.candidates.length*20);i("source_import",Ne,`Lidas ${Math.min(x+se.length,o.candidates.length)} de ${o.candidates.length} fontes.`)}i("projection_build",74,"Organizando fatos e proje\xE7\xF5es do banco local.");let me=u.prepare("SELECT path, content FROM files WHERE (path LIKE '.agents/data/%' OR path LIKE '.agents/records/%') AND path NOT LIKE '.agents/data/runs/%' AND path NOT LIKE '.agents/records/runs/%' ORDER BY CASE WHEN path LIKE '.agents/data/%' THEN 1 ELSE 0 END, path").all(),Le=new Map(me.flatMap(x=>F.read("entities",x.path,X(x.path),()=>[...zb([x])])));for(let x of me)if(h.has(x.path)&&/^\.agents\/(?:data|records)\/specs\//.test(x.path))for(let[,se]of F.read("entities",x.path,X(x.path),()=>[...zb([x])]))se.creationRunId&&le.add(se.creationRunId);i("projection_entities",75,"Entidades can\xF4nicas interpretadas.");let Ce=u.prepare("INSERT INTO canonical_work_items(entity_kind, id, title, status, stage, risk, priority, spec_id, prd_id, change_id, creation_run_id, completed_run_id, occurred_at, occurred_day_sp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");for(let x of Le.values())x.kind!=="task"&&x.kind!=="spec"&&x.kind!=="prd"||x.occurredAt===null||Number.isNaN(Date.parse(x.occurredAt))||Ce.run(x.kind,x.id,x.title,x.status,x.stage,x.risk,x.priority,x.specId,x.prdId,x.changeId,x.creationRunId,x.completedRunId,x.occurredAt,bt(x.occurredAt));let Pe={executions:[],changes:[],decisions:[]};for(let x of me){if(!om(x.path))continue;let se=F.read("lifecycle",x.path,X(x.path),()=>w$([x]));Pe.executions.push(...se.executions),Pe.changes.push(...se.changes),Pe.decisions.push(...se.decisions)}Pe.executions=[...new Map(Pe.executions.map(x=>[x.id,x])).values()],Pe.changes=[...new Map(Pe.changes.map(x=>[x.id,x])).values()],Pe.decisions=[...new Map(Pe.decisions.map(x=>[x.id,x])).values()],i("projection_lifecycle",76,"Registros de ciclo de vida interpretados.");let rn=u.prepare("INSERT INTO canonical_executions(id, status, kind, origin_type, origin_id, created_at, occurred_day_sp, finished_at, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");for(let x of Pe.executions)rn.run(x.id,x.status,x.kind,x.originType,x.originId,x.createdAt,bt(x.createdAt),x.finishedAt,x.sourcePath);let Y=u.prepare("INSERT INTO canonical_changes(id, title, status, risk, source_type, source_id, source_spec_id, source_prd_id, requirement_ids_json, acceptance_ids_json, task_ids_json, result, created_at, occurred_day_sp, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");for(let x of Pe.changes)Y.run(x.id,x.title,x.status,x.risk,x.sourceType,x.sourceId,x.sourceSpecId,x.sourcePrdId,JSON.stringify(x.requirementIds),JSON.stringify(x.acceptanceIds),JSON.stringify(x.taskIds),x.result,x.createdAt,bt(x.createdAt),x.sourcePath);let ce=u.prepare("INSERT INTO canonical_decisions(id, title, origin, scope_type, scope_id, created_at, occurred_day_sp, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");for(let x of Pe.decisions)ce.run(x.id,x.title,x.origin,x.scopeType,x.scopeId,x.createdAt,bt(x.createdAt),x.sourcePath);i("projection_runs_started",77,"Construindo fatos das invoca\xE7\xF5es."),zL(Le,Pe.changes);let $e=u.prepare("UPDATE canonical_work_items SET stage=? WHERE entity_kind=? AND id=?");for(let x of Le.values())$e.run(x.stage,x.kind,x.id);let Xe=FL({database:u,previousActivities:k,parsedSources:F,refresh:a,hasPersistentSchema:m,dirtyRunIds:j,changedSources:h,oldIntervals:R,canonicalEntities:Le,entityChanged:J});i("projection_dimensions_started",78,"Construindo dimens\xF5es e agregados."),UL({...Xe,database:u,canonicalEntities:Le,changedCreationRunIds:le,hasPersistentSchema:m,files:A,skipped:I,fingerprint:s}),i("projection_overview_started",79,"Construindo a vis\xE3o geral."),tS(e,u),u.exec("COMMIT;"),i("projection_finalize",80,"Finalizando \xEDndices do banco persistente do dashboard."),d=A}catch(p){throw u.exec("ROLLBACK;"),p}u.exec("PRAGMA busy_timeout=0; PRAGMA wal_checkpoint(TRUNCATE);")}finally{u.close()}let _=r+l;return i("snapshot_ready",86,"O banco SQLite persistente est\xE1 pronto."),na(n),{files:d,path:n,cache:"rebuilt",fingerprint_ms:l,materialize_ms:Math.round(performance.now()-_),refresh:a}}async function po(e,t,n,i={}){let r=e instanceof ct?K8(e,t,n,i):await nl(e,t,n,i);if(!(e instanceof ct))return r;let o=e.firstFoldMonthlyQuick(n),a=n.from===null&&n.to===null?e.firstFoldViewportAllTime().aggregate:o?.aggregate??e.firstFoldAggregate(n);return{...r,summary:{...r.summary,projection_updated_at:e.projectionUpdatedAt(),latest_token_collected_at:e.latestTokenCollectedAt(),run_count:a.total_run_count,overview_metrics:{...r.summary.overview_metrics,duration_ms:a.duration_ms,tokens:a.total_tokens,cost_brl:a.cost_brl,execution_day_count:a.execution_day_count,data_source:"run_records"}}}}function K8(e,t,n,i){let r=e.firstFoldMonthlyQuick(n),o=n.from===null&&n.to===null&&i.includeExtended===!0?e.firstFoldAllTime():null,a=o??(n.from===null&&n.to===null?e.firstFoldViewportAllTime():null),s=n.from===null&&n.to===null&&i.includeBoardTasks===!0?e.firstFoldBoardAllTime():null,l=j=>r?.pages[j]??s?.pages[j]??e.canonicalWorkPage(j,n,0,1e4).rows,c=a===null||i.includeBoardTasks===!0,u=c?l("task"):[],d=c?l("spec"):[],_=c?l("prd"):[],p=a?.aggregate??r?.aggregate??e.firstFoldAggregate(n),g=a?.task_status_counts.draft??0,m=a===null?u.length:Math.max(0,a.aggregate.task_count-g),f=n.from===null&&n.to===null&&(o!==null||i.includeTopTasks===!0)?o?.top_tasks??e.firstFoldTopTasksAllTime():null,v=f===null?(r?.top_tasks??e.topTasks(n)).map(j=>({task_id:j.task_id,duration_ms:j.duration_ms,total_tokens:j.total_tokens,cost_brl:j.cost_brl,run_count:j.run_count})):Qp(f),S=a===null?null:o?.macro_metrics??e.firstFoldMacroMetrics(),b=S===null?{specs:Pb(d,"spec"),prds:Pb(_,"prd")}:Object.fromEntries(["specs","prds"].map(j=>{let Q=S[j];return[j,{status_counts:Q.status_counts,classification_counts:Q.classification_counts,entity_count:Q.entity_count,total_run_count:Q.total_run_count,total_duration_ms:Q.total_duration_ms,total_tokens:Q.total_tokens,total_cost_usd:Q.total_cost_usd,total_cost_brl:Q.total_cost_brl,average_duration_ms:Q.average_duration_ms,average_tokens:Q.average_tokens,average_cost_usd:Q.average_cost_usd,average_cost_brl:Q.average_cost_brl,latest_created_at:Q.latest_created_at,top_entities:Q.top_entities.map(C=>({entity_id:C.entity_id,title:C.title,duration_ms:C.total_duration_ms,total_tokens:C.total_tokens,total_cost_usd:C.total_cost_usd,cost_brl:C.total_cost_brl,run_count:C.total_run_count,duration_share:C.duration_share}))}]})),h=Object.fromEntries(Object.entries(a?.task_status_counts??{}).filter(([j])=>j!=="draft")),k=a?.task_risk_counts??{};if(a===null)for(let j of u){let Q=typeof j.status=="string"?j.status:"draft",C=typeof j.risk=="string"?j.risk:"standard";h[Q]=(h[Q]??0)+1,k[C]=(k[C]??0)+1}let P=a?.aggregate.latest_task_created_at??[...u,...d,..._].map(j=>typeof j.occurred_at=="string"?j.occurred_at:null).filter(j=>j!==null).sort().at(-1)??null,U={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}},$={...U,tokens:{...U.tokens,total:p.total_tokens},cost:{...U.cost,brl:p.cost_brl}},B={conversation:U,planning:U,execution:U,total:$,new_work:U,rework:U},z=i.includePeriods===!0?e.dailyPeriods(n):{},R=Object.values(z).some(j=>j.usage.total_tokens.unknown>0||j.usage.cost.unknown>0),L=e.canonicalSource(),J=j=>({schema_version:2,id:String(j.id),revision:1,change_id:typeof j.change_id=="string"?j.change_id:"",title:String(j.title??j.id),short_name:String(j.title??j.id),objective:"",status:X8(j.status),attempt_count:null,risk:Y8(j.risk),priority:"medium",owner:null,requirement_ids:[],acceptance_ids:[],depends_on:[],write_scopes:[],created_at:String(j.occurred_at),updated_at:String(j.occurred_at),started_at:null,finished_at:null,result:null,artifact_path:L,progress:0,spec_id:typeof j.spec_id=="string"?j.spec_id:null,origin:typeof j.origin=="string"?j.origin:null,execution_started:!1,telemetry:{duration_ms:ci(j.total_duration),tokens:ci(j.total_tokens),cost_brl:ci(j.total_cost_brl)}}),le=(j,Q)=>{let C={...U,tokens:{...U.tokens,total:ci(j.total_tokens)},cost:{...U.cost,brl:ci(j.total_cost_brl)}};return{id:String(j.id),title:String(j.title??j.id),created_at:String(j.occurred_at),updated_at:String(j.occurred_at),kind:Q,parent_id:Q==="spec"&&typeof j.prd_id=="string"?j.prd_id:null,artifact_path:L,lifecycle_status:String(j.status??"draft"),work_status:Q8(j.stage??j.status),execution_ids:[],task_ids:typeof j.task_ids_json=="string"?JSON.parse(j.task_ids_json):[],planned_tasks:[],canonical_run_ids:[],run_ids:[],root_execution_run_ids:[],execution_count:0,task_count:ci(j.task_count)??0,run_count:ci(j.invocation_count)??0,duration_ms:ci(j.total_duration),decisions:{human:0,agent:0},rework_run_count:ci(j.rework_run_count)??0,quality:{completed_tasks:ci(j.completed_task_count)??0,task_completion_rate:Number(j.task_count)>0?Number(j.completed_task_count??0)/Number(j.task_count):0,terminal_runs:0,successful_runs:0,terminal_success_rate:0,rework_rate:0},usage:{conversation:U,planning:U,execution:U,total:C,new_work:U,rework:U}}};return{schema_version:2,layout_version:t.version,readonly:!0,source:L,filters:n,summary:{prd_count:a?.aggregate.prd_count??_.length,spec_count:a?.aggregate.spec_count??d.length,execution_count:0,task_count:m,run_count:p.total_run_count,overview_metrics:{duration_ms:p.duration_ms,execution_day_count:p.execution_day_count,tokens:p.total_tokens,cost_brl:p.cost_brl,prd_count:a?.aggregate.prd_count??_.length,spec_count:a?.aggregate.spec_count??d.length,selected_counts:{prds:a?.aggregate.prd_count??_.length,specs:a?.aggregate.spec_count??d.length},task_count:m,completed_prd_count:a?.aggregate.completed_prd_count??b.prds.status_counts.completed??0,completed_spec_count:a?.aggregate.completed_spec_count??b.specs.status_counts.completed??0,completed_task_count:a?.aggregate.completed_task_count??h.completed??0,task_status_counts:h,task_risk_counts:k,top_tasks:v,...b===void 0?{}:{macro_metrics:b},latest_task_created_at:P,coverage:{duration:1,tokens:R?0:1,cost:R?0:1},data_source:"run_records",partial:!0},decisions:{human:0,agent:0},source_latest_at:P,quality:{completed_tasks:h.completed??0,task_completion_rate:m===0?0:(a?.aggregate.completed_task_count??h.completed??0)/m,terminal_runs:0,successful_runs:0,terminal_success_rate:0,rework_rate:0},reconciliation:{phase_tokens_match_total:!0,phase_usd_match_total:!0,phase_brl_match_total:!0,origin_tokens_match_total:!0},usage:B,periods:{daily:i.includePeriods===!0?z:{}}},origins:{conversation:B,task:B,spec:B,prd:B},prds:_.map(j=>le(j,"prd")),specs:d.map(j=>le(j,"spec")),tasks:i.includeBoardTasks?u.map(J):[],changes:[],executions:[],runs:[],decisions:[],evidences:[],validations:[]}}function ci(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function X8(e){return["draft","planned","executing","verifying","completed","failed","blocked","cancelled"].includes(String(e))?String(e):"draft"}function Y8(e){return["lite","standard","critical"].includes(String(e))?String(e):"standard"}function Q8(e){let t=String(e);return["executing","verifying","completed","blocked","failed","cancelled"].includes(t)?t:"planning"}async function sS(e,t={from:null,to:null}){if(e instanceof ct)return e.costMonitorSummaryAggregate(t);let n=await new Bt(e).readDailyReadModels("overview");if(n===null)throw new Error("Lifecycle daily overview is not initialized");return{periods:{daily:Object.fromEntries(Object.entries(n.days).map(([i,r])=>[i,r.overview]))}}}async function WL(e,t,n,i){let r=i??await Ai(e),{from:o,to:a}=Et(n),s=Jn(n),l=e instanceof ct?await po(e,r,{from:o,to:a}):await as(e,r,{from:o,to:a}),c=e instanceof ct?Gp(await sS(e,{from:o,to:a}),l,s,s==="BRL"?(await al(e))?.rate??null:null):await os(e,l,s);return{operations:l,costs:c,dashboard:await tm(e,t),projection:{source_latest_at:l.summary.source_latest_at,updated_at:l.summary.projection_updated_at??null,latest_token_collected_at:l.summary.latest_token_collected_at??null,served_at:new Date().toISOString()}}}function BL(e,t){let{filesystem:n,canonicalFilesystem:i,isSqliteSnapshot:r,readLayout:o,readSnapshot:a,readAggregate:s,clearSnapshotCache:l}=t;e.on(["GET","HEAD"],`${Se}/cost-monitor`,async c=>{try{let u=c.req.query("scope")??"summary";if(u==="summary"){let m=await o(),{from:f,to:v}=Et(c),S=Jn(c),b=performance.now(),[h,k]=await Promise.all([sS(n,{query:c.req.query("query")??"",from:f,to:v,providers:tt(c,"provider"),models:tt(c,"model"),agents:tt(c,"agent"),phases:tt(c,"phase"),statuses:tt(c,"status"),tasks:tt(c,"task"),specs:tt(c,"spec"),prds:tt(c,"prd"),executions:tt(c,"execution"),changes:tt(c,"change"),priorities:tt(c,"priority"),risks:tt(c,"risk"),origins:tt(c,"origin"),workTypes:[...new Set([...tt(c,"workType"),...tt(c,"work_type")])]}),S==="BRL"?al(n):Promise.resolve(null)]),P=performance.now()-b,U={schema_version:1,layout_version:m.version,readonly:!0,source:".agents/records",filters:{from:f,to:v},summary:{task_count:h.task_count??0},prds:[],specs:[],runs:[]},$=performance.now(),B=Gp(h,U,S,k?.rate??null);return c.header("Server-Timing",`cost_sql;dur=${P.toFixed(1)},cost_projection;dur=${(performance.now()-$).toFixed(1)}`),ye(c,B,200,!0)}if(u==="runs"){let m=await o(),{from:f,to:v}=Et(c),S=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),b=Math.min(500,Math.max(1,Number.parseInt(c.req.query("limit")??"100",10)||100));return ye(c,await c$(r?i:n,m,c,{from:f,to:v},S,b),200,!0)}if(Ib(c))return ye(c,(await a(c)).costs);let d=await o(),{from:_,to:p}=Et(c),g=await as(n,d,{from:_,to:p});return ye(c,await a$(n,g,c))}catch(u){if(u instanceof Dt)throw u;return ye(c,{error:u instanceof Error?u.message:String(u)},400)}}),e.on(["GET","HEAD"],`${Se}/developers`,async c=>{if(!(n instanceof ct))return ye(c,{error:"Developer attribution requires the SQLite read model"},409);let{from:u,to:d}=Et(c);return ye(c,n.developerCostAggregate({from:u,to:d,accountIds:tt(c,"account_id")}),200,!0)}),e.on(["GET","HEAD"],`${Se}/operations/developers`,async c=>{if(!(n instanceof ct))return ye(c,{error:"Developer attribution requires the SQLite read model"},409);let{from:u,to:d}=Et(c);return ye(c,n.operationsDeveloperAggregate({from:u,to:d,accountIds:tt(c,"account_id")}),200,!0)})}ea();ri();function ZL(e){return{query:(e.req.query("query")??"").trim().toLocaleLowerCase(),status:e.req.query("status")??"",risk:e.req.query("risk")??"",origin:e.req.query("origin")??"",kind:e.req.query("kind")??""}}function HL(e){if(e===void 0||!["definition","planning","ready","executing","verifying","completed","blocked","cancelled","failed"].includes(e))throw new Error("A valid Kanban stage is required");return e}function JL(e,t,n,i,r,o){let a=new Map(e.changes.map(b=>[b.id,b.source.type])),s=b=>{let h=b.origin;return a.get(b.change_id)??(typeof h=="string"?h:b.spec_id===null?"task":"spec")},l=b=>o.query===""||b.some(h=>h?.toLocaleLowerCase().includes(o.query)),c=b=>(o.status===""||ss(b)===o.status)&&(o.risk===""||b.risk===o.risk)&&(o.origin===""||s(b)===o.origin)&&l([b.id,b.title,b.short_name,b.objective,b.change_id,b.spec_id]),u=b=>o.risk===""&&o.origin===""&&(o.status===""||im(b,e.tasks)===o.status)&&l([b.id,b.title,b.parent_id]),d=e.tasks.filter(c),_=e.prds.filter(u),p=e.specs.filter(u),m=[..._.map(b=>({kind:"prd",row:b})),...p.map(b=>({kind:"spec",row:b})),...d.map(b=>({kind:"task",row:b}))].filter(b=>(b.kind==="task"?ss(b.row):im(b.row,e.tasks))===t).toSorted((b,h)=>{let k=new Map(r.map((P,U)=>[P,U]));return(k.get(b.row.id)??Number.MAX_SAFE_INTEGER)-(k.get(h.row.id)??Number.MAX_SAFE_INTEGER)||String(h.row.updated_at??"").localeCompare(String(b.row.updated_at??""))||b.row.id.localeCompare(h.row.id)}).filter(b=>(b.kind==="task"?ss(b.row):im(b.row,e.tasks))===t),f=o.kind===""?m:o.kind==="all-tasks"?m.filter(b=>b.kind==="task"):o.kind==="standalone-task"?m.filter(b=>b.kind==="task"&&b.row.spec_id===null):o.kind==="task"?m.filter(b=>b.kind==="task"&&b.row.spec_id!==null):m.filter(b=>b.kind===o.kind),v=f.slice(n,n+i),S=new Set(v.map(b=>b.row.id));return{stage:t,offset:n,total:f.length,totals_by_kind:{all:m.length,task:m.filter(b=>b.kind==="task"&&b.row.spec_id!==null).length,"standalone-task":m.filter(b=>b.kind==="task"&&b.row.spec_id===null).length,prd:m.filter(b=>b.kind==="prd").length,spec:m.filter(b=>b.kind==="spec").length},prds:v.filter(b=>b.kind==="prd").map(b=>b.row),specs:v.filter(b=>b.kind==="spec").map(b=>b.row),tasks:v.filter(b=>b.kind==="task").map(b=>b.row),changes:e.changes.filter(b=>b.task_ids.some(h=>S.has(h)))}}function GL(e,t,n,i,r){let o=c=>c.rework_run_count>0?"rework":c.task_count>0?"structured":"empty",s=(t==="task"?e.tasks.filter(c=>c.risk===n):(t==="spec"?e.specs:e.prds).filter(c=>o(c)===n)).toSorted((c,u)=>String(u.updated_at??u.created_at??"").localeCompare(String(c.updated_at??c.created_at??""))||c.id.localeCompare(u.id)),l=s.slice(i,i+r);return{offset:i,total:s.length,prds:t==="prd"?l:[],specs:t==="spec"?l:[],tasks:t==="task"?l:[],changes:t==="task"?e.changes.filter(c=>l.some(u=>c.task_ids.includes(u.id))):[]}}ri();ri();function Sm(e,t,n,i,r,o,a=null){let s=Object.entries(e.days).sort(([S],[b])=>b.localeCompare(S)),l=n.from===null?null:KL(n.from),c=n.to===null?null:KL(n.to),u=s.filter(([S])=>(l===null||S>=l)&&(c===null||S<=c)),_=(t==="overview"?u.map(([S,b])=>({day:S,...b.overview})):eQ(t,XL(u.flatMap(([,S])=>S[t])),XL(s.flatMap(([,S])=>S[t])),n)).filter(S=>rQ(S,i)),p=nQ(a),g=p===null?_:_.filter(S=>`${YL(S)}\0${QL(S)}`<p),m=p===null?r:0,f=g.slice(m,m+o),v=f.at(-1);return{data_source:"lifecycle_daily_read_models",snapshot_id:e.updated_at,source_latest_at:e.source_latest_at,kind:t,offset:m,limit:o,total:_.length,has_more:m+o<g.length,next_cursor:v===void 0||m+o>=g.length?null:tQ(YL(v),QL(v)),rows:f}}function KL(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)?e:nn(e,"day")}function eQ(e,t,n,i){if(e!=="tasks"&&e!=="specs"&&e!=="prds")return[...t];let r=new Set(["completed","delivered","failed","cancelled","superseded","rolled_back"]),o=new Map(n.map(c=>[c.id,c])),a=t.filter(c=>{let u=o.get(c.id)??c;if(u.status===null||!r.has(u.status)||c.run_count>0)return!0;let d=u.window_at??u.occurred_at;return(i.from===null||d>=i.from)&&(i.to===null||d<=i.to)}),s=new Set(a.map(c=>c.id)),l=()=>({known_sum:0,unknown:0,complete:!0,coverage_ratio:1});return[...a,...n.filter(c=>!s.has(c.id)&&(c.status===null||!r.has(c.status))).map(c=>({...c,run_count:0,cost_currency:null,metrics:{duration:l(),total_tokens:l(),cost:l()}}))].sort((c,u)=>u.occurred_at.localeCompare(c.occurred_at)||c.id.localeCompare(u.id))}function XL(e){let t=new Map;for(let n of e){let i=t.get(n.id);if(i===void 0){t.set(n.id,structuredClone(n));continue}let r=i.run_count;if(n.run_count>0){let o=n.lifecycle_elapsed_ms??null;if(r===0)i.lifecycle_elapsed_ms=o;else{let a=i.lifecycle_elapsed_ms??null;i.lifecycle_elapsed_ms=a===null||o===null?null:a+o}}i.run_count+=n.run_count;for(let o of["duration","total_tokens","cost"]){let a=i.metrics[o],s=n.metrics[o];a.known_sum+=s.known_sum,a.unknown+=s.unknown,a.complete=a.unknown===0;let l=i.run_count;a.coverage_ratio=l===0?1:Math.max(0,Math.min(1,(l-a.unknown)/l))}}return[...t.values()].sort((n,i)=>i.occurred_at.localeCompare(n.occurred_at)||n.id.localeCompare(i.id))}function YL(e){let t=e;return typeof t.occurred_at=="string"?t.occurred_at:typeof t.day=="string"?t.day:""}function QL(e){let t=e;return typeof t.id=="string"?t.id:typeof t.day=="string"?t.day:""}function tQ(e,t){return encodeURIComponent(JSON.stringify([e,t]))}function nQ(e){if(e===null)return null;try{let t=JSON.parse(decodeURIComponent(e));return Array.isArray(t)&&typeof t[0]=="string"&&typeof t[1]=="string"?`${t[0]}\0${t[1]}`:null}catch{return null}}function rQ(e,t){return t.status&&e.status!==t.status||t.risk&&e.risk!==t.risk?!1:t.query?Object.values(e).some(n=>typeof n=="string"&&n.toLocaleLowerCase().includes(t.query)):!0}var eM=require("node:path");function mo(e){return{query:(e.req.query("query")??"").trim().toLocaleLowerCase(),status:(e.req.query("status")??"").trim(),risk:(e.req.query("risk")??"").trim()}}function cS(e,t){return e.filter(n=>t.status&&n.status!==t.status?!1:t.query?[n.id,n.task_id,n.execution_id,n.conversation_id,n.parent_run_id,n.run_kind,n.phase,n.agent].some(i=>typeof i=="string"&&i.toLocaleLowerCase().includes(t.query)):!0)}function lS(e,t){return e.filter(n=>t.status&&n.status!==t.status||t.risk&&n.risk!==t.risk?!1:t.query?[n.id,n.title,n.status,n.risk,n.source,n.origin,n.scope_type,n.scope_id].flatMap(i=>typeof i=="object"&&i!==null?Object.values(i):[i]).some(i=>typeof i=="string"&&i.toLocaleLowerCase().includes(t.query)):!0)}function tM(e,t){if(t!=="executions"&&t!=="conversations")return[...e];let n=new Map;for(let i of e){let r=t==="executions"?i.execution_id:i.conversation_id;if(r==null)continue;let o=n.get(r)??{...i,id:r,duration_ms:null,total_tokens:null,cost:null};i.phase==="execution"&&i.parent_run_id===null&&i.duration_ms!==null&&(o.duration_ms=(o.duration_ms??0)+i.duration_ms),i.total_tokens!==null&&(o.total_tokens=(o.total_tokens??0)+i.total_tokens),i.cost!==null&&(o.cost=(o.cost??0)+i.cost);let a=o.finished_at??o.started_at;(i.finished_at??i.started_at)>a&&(o.status=i.status),i.started_at<o.started_at&&(o.started_at=i.started_at),(o.finished_at===null||i.finished_at!==null&&i.finished_at>o.finished_at)&&(o.finished_at=i.finished_at),n.set(r,o)}return[...n.values()].sort((i,r)=>r.started_at.localeCompare(i.started_at))}function nM(e,t,n,i=[]){let r=new Map;if(n==="conversations")for(let a of i)r.set(a.id,a.status);let o=new Map;for(let a of t){let s=a.data?.origin!==null&&typeof a.data?.origin=="object"?a.data.origin.conversation_id:null,l=n==="executions"?a.id:typeof s=="string"?s:null;l===null||r.has(l)||(n==="executions"?r.set(l,a.status):o.has(l)?o.set(l,null):o.set(l,a.status))}for(let[a,s]of o)r.set(a,s);return e.map(a=>{let s=n==="executions"?a.execution_id:a.conversation_id;return s==null||!r.has(s)?a:{...a,status:r.get(s)??null}})}function rM(e,t,n,i){return e.flatMap(r=>{let o=r.data,a=typeof o?.created_at=="string"?o.created_at:null;if(a===null||n!==null&&a<n||i!==null&&a>i)return[];let s=o?.source;if(s===null||typeof s!="object"||!("type"in s))return[];let l=s;return l.type==="task"&&typeof l.task_id=="string"||l.type==="spec"&&typeof l.spec_id=="string"||l.type==="prd"&&typeof l.prd_id=="string"?[{id:r.id,title:r.title??(typeof o?.title=="string"?o.title:r.id),created_at:a,status:r.status??(typeof o?.status=="string"?o.status:"unclassified"),risk:r.risk??(typeof o?.risk=="string"?o.risk:"unclassified"),source:l,requirement_ids:uS(o?.requirement_ids),acceptance_ids:uS(o?.acceptance_ids),task_ids:uS(o?.task_ids),result:typeof o?.result=="string"?o.result:null,artifact_path:t.activePath("change",r.id)}]:[]}).sort((r,o)=>o.created_at.localeCompare(r.created_at))}function iM(e,t,n,i){return e.flatMap(r=>{let o=r.data,a=typeof o?.created_at=="string"?o.created_at:null;return a===null||n!==null&&a<n||i!==null&&a>i||o?.origin!=="human"&&o?.origin!=="agent"||o?.scope_type!=="change"&&o?.scope_type!=="execution"||typeof o?.scope_id!="string"?[]:[{id:r.id,title:r.title??(typeof o?.title=="string"?o.title:r.id),origin:o.origin,scope_type:o.scope_type,scope_id:o.scope_id,artifact_path:`${eM.posix.dirname(t.activePath(o.scope_type,o.scope_id))}/decisions/${r.id}.md`,created_at:a}]}).sort((r,o)=>o.created_at.localeCompare(r.created_at))}function uS(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function oM(e,t,n,i){e.on(["GET","HEAD"],"/api/v2/operations/read-models",async r=>{let o=r.req.query("kind");if(!["overview","tasks","specs","prds","executions","conversations"].includes(o))return i(r,{error:"Unsupported daily read model"},400,!1);let a=Math.max(0,Number.parseInt(r.req.query("offset")??"0",10)||0),s=Math.min(200,Math.max(1,Number.parseInt(r.req.query("limit")??"20",10)||20)),{from:l,to:c}=Et(r),u=mo(r),d=await n(`operations:read-model:${o}:${l??""}:${c??""}:${a}:${s}:${r.req.query("cursor")??""}:${u.query}:${u.status}:${u.risk}`,async()=>{let _=await new Bt(t).readDailyReadModels(o);return _===null?{data_source:"lifecycle_daily_read_models",snapshot_id:null,source_latest_at:null,kind:o,offset:a,limit:s,total:0,has_more:!1,next_cursor:null,rows:[]}:Sm(_,o,{from:l,to:c},u,a,s,r.req.query("cursor")??null)});return i(r,d,200,!0)})}ri();function aM(e,t,n,i){e.on(["GET","HEAD"],"/api/v2/operations/runs",async r=>{let o=Math.max(0,Number.parseInt(r.req.query("offset")??"0",10)||0),a=Math.min(200,Math.max(1,Number.parseInt(r.req.query("limit")??"100",10)||100)),{from:s,to:l}=Et(r),c=r.req.query("kind")??"runs";if(c!=="runs"&&c!=="executions"&&c!=="conversations")return i(r,{error:"Unsupported Operations Run page"},400,!1);let u=c,d=mo(r),_=await n(`operations:runs:${u}:${s??""}:${l??""}:${o}:${a}:${d.query}:${d.status}:${d.risk}`,async()=>{if(u==="executions"||u==="conversations"){let h=await new Bt(t).readDailyReadModels(u);if(h!==null){let k=Sm(h,u,{from:s,to:l},d,o,a);return iQ(u,k,k.rows)}}let p=new Bt(t),[g,m]=await Promise.all([t.readText(".agents/records/lifecycle/summary.json"),p.readEntities("execution")]),v=(JSON.parse(g).run_metrics??[]).filter(h=>(s===null||h.started_at>=s)&&(l===null||h.started_at<=l)&&(u==="runs"||u==="conversations"&&h.phase==="conversation"&&h.conversation_id!==null||u==="executions"&&h.execution_id!==null)),S=tM(v,u),b=cS(u==="runs"?S:nM(S,m,u),d);return{data_source:"lifecycle_manifest_summary",kind:u,offset:o,limit:a,total:b.length,rows:b.slice(o,o+a)}});return i(r,_,200,!0)})}function iQ(e,t,n){let i=r=>r.complete||r.known_sum>0?r.known_sum:null;return{data_source:t.data_source,kind:e,offset:t.offset,limit:t.limit,total:t.total,rows:n.map(r=>({id:r.id,started_at:r.occurred_at,finished_at:null,task_id:r.kind==="execution"?r.parent_id:null,execution_id:r.kind==="execution"?r.id:r.parent_id,conversation_id:r.kind==="conversation"?r.id:null,parent_run_id:null,run_kind:"run",phase:r.kind,status:r.status,duration_ms:i(r.metrics.duration),lifecycle_elapsed_ms:r.lifecycle_elapsed_ms??null,total_tokens:i(r.metrics.total_tokens),cost:i(r.metrics.cost),currency:r.cost_currency}))}}function sM(e,t){let{filesystem:n,canonicalFilesystem:i,isSqliteSnapshot:r,readLayout:o,readSnapshot:a,readAggregate:s,clearSnapshotCache:l}=t;e.on(["GET","HEAD"],`${Se}/operations`,async c=>{try{let u=performance.now(),d=c.req.query("scope");if(d!=="overview"&&d!=="quick"&&d!=="detail"&&d!=="board"&&d!=="traceability"&&d!=="classification")return ye(c,(await a(c)).operations);let _=await o(),p=performance.now()-u,{from:g,to:m}=Et(c);if(d==="board"||d==="traceability"){let v=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),S=Math.min(50,Math.max(1,Number.parseInt(c.req.query("limit")??"10",10)||10)),b=await s(`operations:board:${g??""}:${m??""}`,async()=>{let $=await po(n,_,{from:g,to:m},{includeBoardTasks:!0});return{projection:$,priority:await Xp(i,Yp($))}});if(d==="traceability"){let $=b.projection.tasks.toSorted((B,z)=>z.created_at.localeCompare(B.created_at)||z.id.localeCompare(B.id));return ye(c,{tasks:$.slice(v,v+S),total:$.length,offset:v,limit:S},200,!0)}let h=HL(c.req.query("stage")),k=ZL(c),P=JSON.stringify({from:g,to:m,stage:h,offset:v,limit:S,...k}),U=await s(`operations:board-page:${P}`,async()=>JL(b.projection,h,v,S,b.priority.item_ids,k));return ye(c,U,200,!0)}if(d==="classification"){let v=c.req.query("kind"),S=c.req.query("classification");if(v!=="task"&&v!=="spec"&&v!=="prd")return ye(c,{error:"A valid work kind is required"},400);if(!["lite","standard","critical","empty","structured","rework"].includes(S??""))return ye(c,{error:"A valid classification is required"},400);let b=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),h=Math.min(50,Math.max(1,Number.parseInt(c.req.query("limit")??"50",10)||50)),k=await s(`operations:classification:${g??""}:${m??""}`,()=>po(n,_,{from:g,to:m},{includeBoardTasks:!0}));return ye(c,GL(k,v,S,b,h),200,!0)}if(d==="quick"){let v=performance.now(),S=await s(`operations:quick:${g??""}:${m??""}`,()=>po(n,_,{from:g,to:m},{includeTopTasks:g===null&&m===null,includeExtended:g===null&&m===null}),c.req.query("fresh")==="1");if(process.env.ZAIP_DASHBOARD_PROFILE_FIRST_FOLD==="1"&&n instanceof ct){let b=n.firstFoldViewportProfile();c.header("Server-Timing",[`layout;dur=${Math.round(p*10)/10}`,`projection;dur=${Math.round((performance.now()-v)*10)/10}`,...Object.entries(b).map(([h,k])=>`${h};dur=${k}`)].join(", "))}return ye(c,S,200,!0)}let f=n instanceof ct?await po(n,_,{from:g,to:m},{includeBoardTasks:d==="detail",includeExtended:d==="detail"||d==="overview",includePeriods:d==="detail"||d==="overview"}):await as(n,_,{from:g,to:m},d==="overview");return ye(c,f,200,d==="overview")}catch(u){if(u instanceof Dt)throw u;return ye(c,{error:u instanceof Error?u.message:String(u)},400)}}),aM(e,r?i:n,s,ye),e.on(["GET","HEAD"],`${Se}/sqlite-read-models`,async c=>{if(!(n instanceof ct))return ye(c,{error:"SQLite read model is not active"},409);let u=c.req.query("kind"),d=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),_=Math.min(200,Math.max(1,Number.parseInt(c.req.query("limit")??"20",10)||20));if(u==="overview"){let f=c.req.query("period");return f!=="day"&&f!=="month"&&f!=="year"?ye(c,{error:"Unsupported SQLite overview period"},400):ye(c,n.overviewPage(f,d,_),200,!0)}if(u!=="task"&&u!=="spec"&&u!=="prd")return ye(c,{error:"Unsupported SQLite read model"},400);let{from:p,to:g}=Et(c),m=mo(c);return ye(c,n.summaryPage(u,{from:p,to:g,...m},d,_,c.req.query("cursor")??null),200,!0)}),e.on(["GET","HEAD"],`${Se}/sqlite-views`,async c=>{if(!(n instanceof ct))return ye(c,{error:"SQLite read model is not active"},409);let u=c.req.query("view");if(u===void 0||!Object.hasOwn(ra,u))return ye(c,{error:"Unsupported SQLite view"},400);let d=Number.parseInt(c.req.query("limit")??"",10),_=u.includes("agent_invocations")?100:u==="first_fold_top_tasks"?5:50,p=Math.min(200,Math.max(1,Number.isFinite(d)?d:_)),{from:g,to:m}=Et(c),f=S=>{let b=c.req.query(S);return b===void 0?{}:{[S]:b}},v=c.req.query("kind");return u==="operations_work_list"&&v!==void 0&&!["all","task","standalone-task","prd","spec"].includes(v)?ye(c,{error:"Unsupported Operations work-list kind"},400):ye(c,n.viewPage(u,{from:g,to:m,...f("query"),...f("status"),...f("risk"),...f("provider"),...f("model"),...f("agent"),...f("phase"),...f("origin"),...f("workType"),...f("priority"),...v===void 0?{}:{kind:v},offset:Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),limit:p}),200,!0)}),e.on(["GET","HEAD"],`${Se}/work-priority`,async c=>{let u=await Ai(i),d=await il(i,u,{from:null,to:null});return ye(c,await Xp(i,Yp(d)))}),e.on(["GET","HEAD"],`${Se}/operations/entities`,async c=>{let u=Math.max(0,Number.parseInt(c.req.query("offset")??"0",10)||0),d=Math.min(500,Math.max(1,Number.parseInt(c.req.query("limit")??"100",10)||100)),_=c.req.query("kind");if(_!=="changes"&&_!=="decisions")return ye(c,{error:"Unsupported Operations entity page"},400);let{from:p,to:g}=Et(c),m=mo(c),f=await s(`operations:entities:${_}:${p??""}:${g??""}:${u}:${d}:${m.query}:${m.status}:${m.risk}`,async()=>{let v=await o(),S=await new Bt(n).readEntities(_==="changes"?"change":"decision"),b=_==="changes"?rM(S,v,p,g):iM(S,v,p,g),h=lS(b,m);return{data_source:"lifecycle_manifest_shards",kind:_,offset:u,limit:d,total:h.length,rows:h.slice(u,u+d)}});return ye(c,f,200,!0)}),oM(e,n,s,ye),e.put(`${Se}/work-priority`,async c=>{let u=Nb(await c.req.json());return await i.writeTextAtomic(cC,`${JSON.stringify(u,null,2)}
|
|
2320
2320
|
`),l(),c.json(u)}),e.on(["GET","HEAD"],`${Se}/snapshot`,async c=>{try{return ye(c,await a(c))}catch(u){if(u instanceof Dt)throw u;return ye(c,{error:u instanceof Error?u.message:String(u)},400)}})}var dS=require("node:crypto");function cM(e){return e.reconciled_ids.length>0||e.blocked.length>0}async function lM(e,t=()=>{}){let n;try{return await Promise.race([e,new Promise((i,r)=>{n=setTimeout(()=>{t(),r(new ta)},rm),n.unref()})])}finally{n!==void 0&&clearTimeout(n)}}function uM(e){let t=Promise.resolve(),n=new Map,i=new WeakMap,r=a=>{e.refresh(a).catch(()=>{})};return Object.assign((a,s)=>{let l=n.get(a);if(l!==void 0)return l;let c=t.then(()=>s===void 0?e.reconcile(a):e.reconcile(a,s)).then(u=>((u.reconciled_ids.length>0||u.blocked.length>0)&&r(s),u),u=>{throw r(s),u}).finally(()=>n.delete(a));return n.set(a,c),s!==void 0&&i.set(c,s),t=c.then(()=>{},()=>{}),c},{jobIdFor:a=>i.get(a)??null})}function dM(e){return uM({reconcile:async(t,n)=>{let i=n??(0,dS.randomUUID)(),r=new Date().toISOString();e.diagnostics.log("reconciliation_started",{job_id:i,mode:t});try{let a={...await e.reconcile(t,i),diagnostics:{job_id:i,started_at:r,completed_at:new Date().toISOString(),log_directory:".local/dashboard-logs",...e.snapshotTimes()}};return e.diagnostics.log("reconciliation_completed",{job_id:i,result:a}),a}catch(o){throw e.diagnostics.log("reconciliation_failed",{job_id:i,error:o}),o}},refresh:t=>e.refresh(t??null)})}function _M(e,t){e.post(`${Se}/reconcile-open-work`,async n=>{let i=(0,dS.randomUUID)(),r=null;n.header("X-ZAIP-Request-Id",i),t.diagnostics.log("reconciliation_button_received",{request_id:i});try{await t.readLayout();let o=t.reconcileWork("manual",i);r=t.reconcileWork.jobIdFor(o),t.diagnostics.log("reconciliation_queued",{request_id:i,job_id:r});let a=await lM(o,()=>{t.diagnostics.log("reconciliation_http_deadline",{request_id:i,job_id:r}),t.refresh(r).catch(()=>{})});return t.diagnostics.log("reconciliation_response",{request_id:i,job_id:a.diagnostics?.job_id,snapshot_state:t.snapshotState()}),n.json({reconciliation:a,snapshot_state:t.snapshotState(),projection_refresh_completed:t.refreshCompleted()})}catch(o){if(t.diagnostics.log("reconciliation_response_error",{request_id:i,job_id:r,error:o}),o instanceof Dt)throw o;let a={error:Na(o instanceof Error?o.message:String(o)),request_id:i,job_id:r,log_directory:".local/dashboard-logs"};return o instanceof ta?n.json({...a,reconciliation_may_be_partial:!0,projection_refresh_started:!0},408):n.json(a,400)}})}function pM(e,t){let n=/^(?:localhost|127\.0\.0\.1)(?::[0-9]{1,5})?$/i;try{let i=new URL(e);if(i.protocol!=="http:"||i.username||i.password||!n.test(i.host))return!1;if(t!==void 0){if(!n.test(t))return!1;new URL(`http://${t}`)}return!0}catch{return!1}}zn();function mM(e,t,n){e.on(["GET","HEAD"],`${Se}/pricing`,async i=>ye(i,Lo.parse(JSON.parse(await t.readText(".agents/config/pricing/models.json"))))),e.put(`${Se}/pricing`,async i=>{let r=Lo.parse({...await i.req.json(),updated_at:new Date().toISOString()});return await t.writeTextAtomic(".agents/config/pricing/models.json",`${JSON.stringify(r,null,2)}
|
|
2321
|
-
`),n(),i.json(r)}),e.on(["GET","HEAD"],`${Se}/fx-rate`,async i=>{let r=await new Ti(t).readLatestFxRate();return ye(i,r)}),e.put(`${Se}/fx-rate`,async i=>{let r=$o.pick({rate:!0}).parse(await i.req.json()),o=await new Ti(t).writeCurrentFxRate(r.rate);return n(),i.json(o)})}var fM=require("node:child_process"),gM=require("node:fs"),ds=require("node:path");function
|
|
2321
|
+
`),n(),i.json(r)}),e.on(["GET","HEAD"],`${Se}/fx-rate`,async i=>{let r=await new Ti(t).readLatestFxRate();return ye(i,r)}),e.put(`${Se}/fx-rate`,async i=>{let r=$o.pick({rate:!0}).parse(await i.req.json()),o=await new Ti(t).writeCurrentFxRate(r.rate);return n(),i.json(o)})}var fM=require("node:child_process"),gM=require("node:fs"),ds=require("node:path");function oQ(e,t){let n=JSON.parse(e),i=n?.schema;if(n?.storage_mode!=="sqlite_read_model"||typeof n.path!="string"||(0,ds.resolve)(n.path)!==(0,ds.resolve)(t)||i?.schemaVersion!==Gn||i.tableCount!==ll.length||typeof i.viewCount!="number"||!Number.isSafeInteger(i.viewCount)||i.viewCount<ul.length||typeof i.indexCount!="number"||!Number.isSafeInteger(i.indexCount)||i.indexCount<ls.length)throw new Error("SQLite refresh worker did not return a valid schema receipt for this destination")}async function aQ(e,t){let i=[(0,ds.resolve)(e,".agents/dashboard/packages/local-runtime/scripts/rebuild-sqlite-read-model.mjs"),(0,ds.resolve)(process.cwd(),"scripts/rebuild-sqlite-read-model.mjs"),(0,ds.resolve)(process.cwd(),".agents/dashboard/packages/local-runtime/scripts/rebuild-sqlite-read-model.mjs")].find(r=>(0,gM.existsSync)(r));if(i===void 0)throw new Error("SQLite refresh worker script is unavailable from this runtime checkout");await new Promise((r,o)=>{let a="",s="",l=!1,c=(0,fM.spawn)(process.execPath,[i],{cwd:e,env:{...process.env,ZAIP_WORKSPACE:e,ZAIP_SQLITE_DB_PATH:t,ZAIP_SQLITE_PREFER_LAST_VALID_SEED:"0",ZAIP_DASHBOARD_LAUNCH_PROGRESS:"0"},stdio:["ignore","pipe","pipe"],windowsHide:!0}),u=sQ(c);c.stdout?.setEncoding("utf8"),c.stdout?.on("data",d=>{s.length+d.length>64e3&&(l=!0),l||(s+=d)}),c.stderr?.setEncoding("utf8"),c.stderr?.on("data",d=>{a=`${a}${d}`.slice(-8e3)}),c.once("error",d=>{u(),o(d)}),c.once("close",d=>{if(u(),d!==0){o(new Error(`SQLite refresh worker failed (${d}): ${a.trim()||"no stderr"}`));return}try{if(l)throw new Error("SQLite refresh worker receipt exceeds size limit");oQ(s,t),r()}catch(_){o(_)}})})}function sQ(e,t=process){let n=()=>{try{e.kill("SIGTERM")}catch{}};return t.once("exit",n),()=>t.removeListener("exit",n)}async function hM(e,t){let n=si(e);await aQ(e,n),t.refresh()}var yM=require("node:crypto"),vM=require("node:sqlite");function bM(e){let t=new vM.DatabaseSync(si(e),{readOnly:!0});try{let n=t.prepare("SELECT key, value FROM zaip_vw_read_model_metadata WHERE key IN ('schema_version', 'source_fingerprint')").all(),i=new Map(n.map(r=>[r.key,r.value]));if(!i.has("schema_version")||!i.has("source_fingerprint"))throw new Error("Committed SQLite snapshot metadata is incomplete");return(0,yM.createHash)("sha256").update(i.get("schema_version")).update(":").update(i.get("source_fingerprint")).digest("hex")}finally{t.close()}}var SM=require("node:fs"),kM=require("node:path");function wM(e){let t=u=>{e.refresh().catch(d=>e.onRefreshFailure?.({trigger:u,error:d}))},n=e.watchSources&&process.env.ZAIP_DASHBOARD_WATCH_SOURCES!=="0",i=()=>{(e.synchronizeTelemetry?.()??e.refresh()).catch(u=>e.onRefreshFailure?.({trigger:e.staleSeed?"stale_seed":"source_change",error:u}))};if(n?i():e.staleSeed&&t("stale_seed"),!n)return;let r,o=()=>{r!==void 0&&clearTimeout(r),r=setTimeout(()=>{r=void 0,t("source_change")},300),r.unref()},a=new Map,s=u=>{let d=new Set(u.flatMap(_=>["data","records","config"].map(p=>(0,kM.join)(_,".agents",p))));for(let[_,p]of a)d.has(_)||(p.close(),a.delete(_),o());for(let _ of d)if(!a.has(_))try{let p=(0,SM.watch)(_,{recursive:!0},o);p.unref(),a.set(_,p)}catch{}};s([e.workspaceRoot]);let l=async()=>{if(e.discoverSourceRoots!==void 0)try{s(await e.discoverSourceRoots())}catch(u){e.onRefreshFailure?.({trigger:"source_change",error:u})}};l(),setInterval(()=>{l(),i()},6e4).unref()}function pl(e,t){process.stderr.write(`${JSON.stringify({event:"dashboard_sqlite_startup_phase",phase:t,elapsed_ms:Math.round(performance.now()-e)})}
|
|
2322
2322
|
`)}function EM(e,t){process.stderr.write(`${JSON.stringify({event:"dashboard_sqlite_read_model",elapsed_ms:Math.round(performance.now()-e),cache:t.cache,fingerprint_ms:t.fingerprint_ms,materialize_ms:t.materialize_ms,source_files:t.files})}
|
|
2323
|
-
`)}function AM(e){let t=null,n=!1,i=!1;return{refresh:(o=!1)=>t!==null?(o&&i&&e.refresh().catch(()=>{}),t):(t=(async()=>{try{if(e.capture!==void 0){n=!0;let a=await e.capture();e.onCaptureSuccess?.(a)}}catch(a){e.onCaptureFailure?.(a)}finally{n=!1}i=!0,await e.refresh()})().finally(()=>{i=!1,t=null}),t),get pending(){return t!==null},get capturing(){return n}}}ea();var _s=require("node:crypto");ri();var
|
|
2324
|
-
Evidence reference: ${o}`,recorded_at:r,updated_at:r}))}function
|
|
2325
|
-
Requirement reference: ${r}`,recorded_at:i,updated_at:i}))}function v8(e){return`.agents/records/tasks/${e}.md`}function b8(e,t){return t.match(/^#\s+(.+)$/m)?.[1]?.trim()??e.split("/").at(-1)??e}var OM=require("node:crypto");qe();async function CM(e,t,n){let i=await Ro(e,t,"task",n);if(i===null)throw new Error(`Canonical Task ${n} was not found`);let r={path:i,content:await e.readText(i)},o=f=>{let v=/^---\r?\n([\s\S]*?)\r?\n---/.exec(r.content)?.[1]??"",S=new RegExp(`^${f}:\\s*(.+?)\\s*$`,"m").exec(v)?.[1]?.trim();return S===void 0||S==="null"?null:S.replace(/^['"]|['"]$/g,"")};if(o("id")!==n)throw new Error(`Canonical Task identity mismatch: ${n}`);let a=(f,v)=>o(f)??new RegExp(`\\b${v}[A-Z0-9-]+`).exec(r.content)?.[0]??null,s=a("change_id","CHG-")??n,l=a("spec_id","SPEC-"),c=a("prd_id","PRD-"),u=[n,s,l,c].filter(f=>f!==null),d=e.canonicalTraceFiles(u,25e4).filter(f=>/\.(?:md|json|jsonl|txt|log)$/i.test(f.path)&&f.content.length<=25e4).map(f=>{let v=mS(f.path),S=wm(f.content);return{id:(0,OM.createHash)("sha256").update(f.path).digest("hex").slice(0,16),path:f.path,title:f.content.match(/^#\s+(.+)$/m)?.[1]?.trim()??f.path.split("/").at(-1)??f.path,...v,content:f.content,...S}}),_=pS(d),p=new Set(d.map(f=>f.stage)),g=o("risk"),m=o("status");return{schema_version:2,layout_version:t.version,readonly:!0,source:e.canonicalSource(),task_id:n,task_title:o("title")??r.content.match(/^#\s+(.+)$/m)?.[1]?.trim()??n,task_risk:g==="lite"||g==="standard"||g==="critical"?g:null,task_created_at:o("created_at"),task_progress:m==="completed"?100:m==="verifying"?80:m==="executing"?50:m==="blocked"||m==="failed"||m==="cancelled"?0:10,spec_id:l,prd_id:c,change_id:s,usage:e.taskTraceUsage(n),documents:d,stages:_,coverage:{stages_with_documents:p.size,stages_with_timestamps:_.filter(f=>f.status==="recorded").length,total_stages:6,evidence_count:d.filter(f=>f.kind==="evidence").length,test_count:d.filter(f=>f.kind==="test").length}}}function IM(e,t){let{filesystem:n,readLayout:i}=t;e.on(["GET","HEAD"],`${Se}/tasks/:id`,async r=>{try{let o=await i();return ye(r,await vb(n,o,r.req.param("id")))}catch(o){if(o instanceof Dt)throw o;return ye(r,{error:"Task not found"},404)}}),e.on(["GET","HEAD"],`${Se}/prds/:id`,async r=>{try{let o=await i();return ye(r,await bb(n,o,r.req.param("id")))}catch(o){if(o instanceof Dt)throw o;return ye(r,{error:"PRD not found"},404)}}),e.on(["GET","HEAD"],`${Se}/specs/:id`,async r=>{try{let o=await i();return ye(r,await Sb(n,o,r.req.param("id")))}catch(o){if(o instanceof Dt)throw o;return ye(r,{error:"SPEC not found"},404)}}),e.on(["GET","HEAD"],`${Se}/tasks/:id/trace`,async r=>{try{let o=await i(),a=r.req.param("id");return ye(r,n instanceof ct?await CM(n,o,a):await xM(n,o,a))}catch(o){if(o instanceof Dt)throw o;return ye(r,{error:"Task trace not found"},404)}})}var NM=require("node:crypto"),Em="127.0.0.1";function fS(e){try{let t=new URL(e);return t.protocol==="http:"&&(t.hostname===Em||t.hostname==="localhost")}catch{return!1}}function PM(e){try{let t=decodeURIComponent(e).replaceAll("\\","/");return!t.includes("\0")&&!t.split("/").some(n=>n==="..")}catch{return!1}}function gS(){return process.env.ZAIP_UI_TOKEN??(0,NM.randomBytes)(24).toString("base64url")}function $M(e){if(e.req.method!=="GET"&&e.req.method!=="HEAD"||e.req.path!=="/"&&e.req.path!=="/index.html")return!1;let t=e.req.header("origin");return t!==void 0&&!fS(t)?!1:e.req.header("sec-fetch-site")!=="cross-site"}var fl="zaip-dashboard-sqlite-runtime",LM="zaip-dashboard-sqlite-session",MM=5e3;function yS(e=process.env.ZAIP_WORKSPACE??process.cwd(),t=gS(),n=(0,gl.resolve)(process.env.ZAIP_UI_ROOT??"./dist"),i={}){let r=new Qh,o=x_(e,"runtime");o.log("runtime_app_started",{snapshot_read_only:i.snapshotReadOnly});let a=i.filesystem??new ei(e),s=a instanceof ct,l=s?Ai(a):null,c=async()=>i.layout??l??await Ai(a),u=i.snapshotReadOnly??s,d=i.snapshotState??"current",_=i.canonicalFilesystem??new ei(e),p=i.reconcileOpenWork??m$,g=i.refreshReadModel??(async()=>{s&&await hM(e,a)}),m=nm(e),f=(0,gl.resolve)(e),v=(0,gl.basename)(f),S=i.syncAgentAdapters??(()=>zO(e)),b=new Map,h=new Map,k=new Map,P=new Map,U=async(A,I,he=!1)=>{let me=k.get(A);if(!he&&me!==void 0&&(A.startsWith("operations:board:")||Date.now()-me.cachedAt<MM))return me.payload;let Le=P.get(A);if(Le!==void 0)return he?(await Le,U(A,I,!0)):Le;let Ce=I().then(Pe=>(k.set(A,{payload:Pe,cachedAt:Date.now()}),Pe)).finally(()=>P.delete(A));return P.set(A,Ce),Ce},$=A=>{let{from:I,to:he}=Et(A);return`${Jn(A)}:${I??""}:${he??""}`},B=()=>{h.clear(),k.clear(),P.clear()},z=null,R=QO(),L=null,J=null,le=!1,j=null,Q=!1,C=new Set,F=async(A=null)=>{if(A!==null&&C.add(A),ne.capturing)return ne.refresh();if(j!==null)return Q=!0,j;d="updating";let I=(0,jM.randomUUID)(),he=A;return o.log("projection_refresh_started",{refresh_id:I,job_id:he}),j=(async()=>{let me=0;do Q=!1,await g(),s&&(l=Ai(a)),B(),me+=1;while(Q&&me<2);d="current",R.clear(),o.log("projection_refresh_completed",{refresh_id:I,job_id:[...C][0]??he,job_ids:[...C],projection_updated_at:s?a.projectionUpdatedAt():null,latest_token_collected_at:s?a.latestTokenCollectedAt():null}),Q||C.clear()})().catch(me=>{throw R.record({trigger:"source_change",error:me}),o.log("projection_refresh_failed",{refresh_id:I,job_id:[...C][0]??he,job_ids:[...C],error:me}),C.clear(),me}).finally(()=>{j=null,Q&&(Q=!1,setTimeout(()=>{F().catch(Le=>R.record({trigger:"source_change",error:Le}))},250).unref())}),j},X=i.captureTelemetry??(s&&i.watchSources===!0&&process.env.ZAIP_DASHBOARD_WATCH_SOURCES!=="0"?()=>MO(e):void 0),ne=AM({refresh:F,...X===void 0?{}:{capture:async()=>(j!==null&&await j.catch(()=>{}),X())},onCaptureSuccess:A=>{J=A,L=null,le=A.catch_up_complete===!1},onCaptureFailure:A=>{L=EO(A),o.log("active_telemetry_capture_failed",L)}}),ve=()=>ne.pending||L!==null||le?"updating":d;wM({workspaceRoot:e,discoverSourceRoots:()=>hc(e),staleSeed:s&&d==="updating",watchSources:s&&i.watchSources===!0,refresh:F,synchronizeTelemetry:ne.refresh,onRefreshFailure:R.record});let ge=dM({diagnostics:o,reconcile:(A,I)=>p(_,e,{hostTerminalOnly:A==="host-terminal",jobId:I}),snapshotTimes:()=>({projection_updated_at:s?a.projectionUpdatedAt():null,latest_token_collected_at:s?a.latestTokenCollectedAt():null}),refresh:A=>F(A)}),q=A=>{let I=$(A),he=h.get(I);if(he!==void 0&&Date.now()-he.cachedAt<MM)return A.header("X-ZAIP-Snapshot-Cache","hit"),Promise.resolve(he.snapshot);let me=b.get(I);if(me!==void 0)return A.header("X-ZAIP-Snapshot-Cache","inflight"),me;A.header("X-ZAIP-Snapshot-Cache","miss");let Le=c().then(Ce=>WL(a,e,A,Ce)).then(Ce=>(h.set(I,{snapshot:Ce,cachedAt:Date.now()}),Ce)).finally(()=>{b.delete(I)});return b.set(I,Le),Le};return r.use("*",async(A,I)=>pM(A.req.url,A.req.header("host"))?(A.header("Cache-Control","no-store"),A.header("X-Content-Type-Options","nosniff"),A.header("Referrer-Policy","no-referrer"),A.header("Content-Security-Policy","default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; object-src 'none'; frame-ancestors 'none'"),$M(A)&&kO(A,LM,t,{httpOnly:!0,path:"/",sameSite:"Strict"}),I()):A.json({error:"Host rejected"},403)),r.use(`${Se}/*`,async(A,I)=>{let he=A.req.method==="PUT"&&(A.req.path===`${Se}/work-priority`||A.req.path===`${Se}/project-settings`||!u&&(A.req.path===`${Se}/pricing`||A.req.path===`${Se}/fx-rate`||A.req.path===`${Se}/agent-catalog`)),me=A.req.method==="POST"&&A.req.path===`${Se}/reconcile-open-work`,Le=A.req.method==="GET"&&A.req.path===`${Se}/browser-lease`,Ce=A.req.method==="POST"&&(A.req.path===`${Se}/refresh-projection`||A.req.path===`${Se}/capture-telemetry`);if(A.req.method!=="GET"&&A.req.method!=="HEAD"&&!he&&!me&&!Ce&&!Le)return A.header("Allow",A.req.path===`${Se}/pricing`||A.req.path===`${Se}/fx-rate`||A.req.path===`${Se}/agent-catalog`||A.req.path===`${Se}/project-settings`||A.req.path===`${Se}/work-priority`?"GET, HEAD, PUT":A.req.path===`${Se}/reconcile-open-work`||A.req.path===`${Se}/refresh-projection`||A.req.path===`${Se}/capture-telemetry`?"POST":"GET, HEAD"),A.json({error:"Dashboard API is read-only"},405);if(A.req.path===`${Se}/health`||A.req.path===`${Se}/ready`)return I();let Pe=A.req.header("origin");if(Pe!==void 0&&!fS(Pe))return A.json({error:"Origin rejected"},403);let rn=A.req.header("x-zaip-session"),Y=SO(A,LM),ce=A.req.method==="GET"&&A.req.path.startsWith(`${Se}/agent-catalog-assets/`)?A.req.query("token"):void 0,$e=Le?A.req.query("token"):void 0;return Le&&$e!==t?A.json({error:"Invalid local session"},401):rn!==t&&Y!==t&&ce!==t&&$e!==t?A.json({error:"Invalid local session"},401):I()}),pC(r,Se,i.launcherOwned===!0),r.on(["GET","HEAD"],`${Se}/health`,async A=>{try{let[I,he]=await Promise.all([c(),fc(_)]);return ye(A,{kind:fl,workspaceKey:m,workspace:f,workspace_name:v,server_pid:process.pid,service:"zaip-aios-dashboard",status:he==="initialized"&&L===null&&!le?R.healthStatus:"degraded",api_version:2,workspace_layout:I.version,lifecycle_manifest_state:he,read_only:!0,storage:s?a.metadata():{storage_mode:"filesystem"},snapshot_state:ve(),projection_refresh_failure:R.failure,active_capture_failure:L,active_capture:J})}catch(I){return ye(A,{kind:fl,workspaceKey:m,workspace:f,workspace_name:v,server_pid:process.pid,service:"zaip-aios-dashboard",status:"unavailable",api_version:2,read_only:!0,error:I instanceof Error?I.message:String(I)},503)}}),r.on(["GET","HEAD"],`${Se}/ready`,async A=>{try{let[I,he]=await Promise.all([c(),fc(_)]),me=he==="initialized"&&L===null&&!le?"ready":"degraded";if(s){let Ce=bM(e);z!==null&&z!==Ce&&(a.refresh(),B(),l=Ai(a)),z=Ce;let Pe=a.metadata();return ye(A,{kind:fl,workspaceKey:m,workspace:f,workspace_name:v,server_pid:process.pid,status:me,workspace_layout:I.version,lifecycle_manifest_state:he,storage_mode:Pe.storage_mode,activity_count:Pe.activity_count,day_count:Pe.daily_aggregate_count,snapshot_state:ve(),projection_refresh_failure:R.failure,active_capture_failure:L,active_capture:J,snapshot_revision:Ce,projection_updated_at:a.projectionUpdatedAt(),latest_token_collected_at:a.latestTokenCollectedAt()})}let Le=await po(a,I,{from:null,to:null});return ye(A,{kind:fl,workspaceKey:m,workspace:f,workspace_name:v,server_pid:process.pid,status:me,lifecycle_manifest_state:he,source_latest_at:Le.summary.source_latest_at,active_capture:J})}catch(I){return ye(A,{kind:fl,workspaceKey:m,status:"unavailable",error:I instanceof Error?I.message:String(I)},503)}}),r.on(["GET","HEAD"],`${Se}/dashboard-identity`,async A=>ye(A,await tm(a,e))),sM(r,{filesystem:a,canonicalFilesystem:_,isSqliteSnapshot:s,readLayout:c,readSnapshot:q,readAggregate:U,clearSnapshotCache:B}),_M(r,{readLayout:c,diagnostics:o,reconcileWork:ge,refresh:A=>F(A),snapshotState:ve,refreshCompleted:()=>ve()==="current"&&j===null}),r.post(`${Se}/refresh-projection`,async A=>{try{return await c(),await ne.refresh(!0),L!==null?A.json({error:"Telemetry capture is unavailable",snapshot_state:ve(),active_capture_failure:L},503):A.json(await q(A))}catch(I){if(I instanceof Dt)throw I;return A.json({error:I instanceof Error?I.message:String(I)},400)}}),r.post(`${Se}/capture-telemetry`,async A=>(await c(),ne.refresh().catch(I=>R.record({trigger:"source_change",error:I})),A.json({snapshot_state:ve()},202))),BL(r,{filesystem:a,canonicalFilesystem:_,isSqliteSnapshot:s,readLayout:c,readSnapshot:q,readAggregate:U,clearSnapshotCache:B}),mM(r,a,B),dC(r,{filesystem:a,workspaceRoot:e,syncAgentAdapters:S,clearSnapshotCache:B}),r.on(["GET","HEAD"],`${Se}/project-settings`,async A=>{try{return ye(A,await bc(_))}catch(I){return ye(A,{error:I instanceof Error?I.message:String(I)},400)}}),r.on(["GET","HEAD"],`${Se}/project-settings/overview`,async A=>ye(A,await XO(_))),r.put(`${Se}/project-settings`,async A=>{try{let I=await YO(_,await A.req.json());return B(),A.json(I)}catch(I){return A.json({error:I instanceof Error?I.message:"Project settings update failed"},400)}}),IM(r,{filesystem:a,canonicalFilesystem:_,isSqliteSnapshot:s,readLayout:c,readSnapshot:q,readAggregate:U,clearSnapshotCache:B}),r.onError((A,I)=>{let he=A instanceof Dt?409:500;return ye(I,{error:he===409?A.message:"Dashboard projection failed"},he)}),r.all(`${Se}/*`,A=>ye(A,{error:"Not found"},404)),r.on(["GET","HEAD"],"/",Al({path:`${n}/index.html`})),r.use("/*",async(A,I)=>PM(A.req.path)?I():A.json({error:"Invalid dashboard asset path"},400)),r.use("/*",Al({root:n})),r.on(["GET","HEAD"],"/*",Al({path:`${n}/index.html`})),r}var Am=performance.now(),UM=gS(),Tm=process.env.ZAIP_WORKSPACE??process.cwd(),DM;function hS(){return DM??=yS(Tm,UM),DM}var S8=new Proxy({},{get(e,t){let n=Reflect.get(hS(),t);return typeof n=="function"?n.bind(hS()):n}});async function k8(){let e=Number.parseInt(process.env.ZAIP_SERVER_PORT??"4317",10);pl(Am,"main_entered");let t=performance.now(),i=await _l(Tm,{forceCanonical:!1,preferExisting:!0});EM(t,i),pl(Am,"read_model_ready");let r=yS(Tm,UM,void 0,{filesystem:new ct(Tm),snapshotState:i.cache==="stale_seed"?"updating":"current",watchSources:!0,launcherOwned:!0});pl(Am,"runtime_app_ready"),WS({fetch:r.fetch,hostname:Em,port:e},({port:o})=>{pl(Am,"listening"),process.stdout.write(`ZAIP-AIOS dashboard API: http://${Em}:${o}${Se}/health
|
|
2326
|
-
`)})}(process.argv[1]?.endsWith("server.cjs")||process.argv[1]?.endsWith("server.js")||process.argv[1]?.endsWith("server.mjs"))&&
|
|
2323
|
+
`)}function AM(e){let t=null,n=!1,i=!1;return{refresh:(o=!1)=>t!==null?(o&&i&&e.refresh().catch(()=>{}),t):(t=(async()=>{try{if(e.capture!==void 0){n=!0;let a=await e.capture();e.onCaptureSuccess?.(a)}}catch(a){e.onCaptureFailure?.(a)}finally{n=!1}i=!0,await e.refresh()})().finally(()=>{i=!1,t=null}),t),get pending(){return t!==null},get capturing(){return n}}}ea();var _s=require("node:crypto");ri();var cQ=25e4;async function xM(e,t,n){if(t.version===1)throw new Error("Task trace requires a modern WorkspaceLayout");let i=await new Bt(e).readEntities(),r=i.find(h=>h.kind==="task"&&h.id===n);if(r===void 0)throw new Error(`Task ${n} was not found in the lifecycle manifest`);let o=li(r,"change_id")??ml(r,"CHG-")??r.id,a=i.find(h=>h.kind==="change"&&h.id===o),s=TM(a,"spec_id")??ml(r,"SPEC-")??ml(a,"SPEC-"),l=TM(a,"prd_id")??ml(r,"PRD-")??ml(a,"PRD-"),c=new Set([r.id,o]);s!==null&&c.add(s),l!==null&&c.add(l);let u=new Set([...r.relations,...a?.relations??[]].filter(h=>/^(?:REQ|AC)-/.test(h))),d=i.filter(h=>pQ(h,c)),_=d.filter(h=>h.kind==="run"&&li(h,"task_id")===r.id),p=new Set;for(let h of d)h.kind!=="decision"&&h.kind!=="evidence"&&h.kind!=="validation"&&p.add(t.activePath(h.kind,h.id));p.add(t.activePath("task",r.id)),o.startsWith("CHG-")&&p.add(t.activePath("change",o)),s!==null&&p.add(t.activePath("spec",s)),l!==null&&p.add(t.activePath("prd",l));let g=new Set(p),m=await Promise.all(lQ(p).map(h=>e.listFiles(h)));for(let h of m.flat())g.add(h);let f=[],v=li(r,"finished_at");for(let h of g){if(!/\.(?:md|json|jsonl|txt|log)$/i.test(h)||!await e.exists(h))continue;let k=await e.readText(h);if(k.length>cQ||!(!h.includes("/requirements/")||[...u].some(le=>k.includes(le))))continue;let $=mS(h),B=wm(k),z=($.kind==="evidence"||$.kind==="test"||$.kind==="eval"||$.kind==="check")&&k.includes(r.id);if(($.kind==="evidence"||$.kind==="test"||$.kind==="eval"||$.kind==="check")&&!z)continue;let R={id:(0,_s.createHash)("sha256").update(h).digest("hex").slice(0,16),path:h,title:bQ(h,k),...$,content:k,recorded_at:B.recorded_at??(z?v:null),updated_at:B.updated_at??(z?v:null)};f.push(R);let L=fQ(R);L!==null&&f.push(L);let J=gQ(R,r.id);J!==null&&f.push(J)}for(let h of yQ(r,u,f))f.push(h);for(let h of hQ(r,f))f.push(h);f.sort((h,k)=>_S[h.stage]-_S[k.stage]||h.path.localeCompare(k.path));let S=new Set(f.map(h=>h.stage)),b=pS(f);return{schema_version:2,layout_version:t.version,readonly:!0,source:".agents/records",task_id:r.id,task_title:r.title??r.id,task_risk:r.risk==="lite"||r.risk==="standard"||r.risk==="critical"?r.risk:null,task_created_at:li(r,"created_at"),task_progress:mQ(r.status),spec_id:s,prd_id:l,change_id:o,usage:uQ(_),documents:f,stages:b,coverage:{stages_with_documents:S.size,stages_with_timestamps:b.filter(h=>h.status==="recorded").length,total_stages:6,evidence_count:f.filter(h=>h.kind==="evidence").length,test_count:f.filter(h=>h.kind==="test").length}}}function lQ(e){let t=new Set;for(let n of e){if(!n.endsWith("/change.md")&&!n.endsWith("/execution.md"))continue;let i=n.slice(0,n.lastIndexOf("/"));t.add(`${i}/decisions`);for(let r of["evidence","tests","evals","checks"])t.add(`${i}/artifacts/${r}`)}return[...t].sort()}function uQ(e,t=Date.now()){let n=e.map(s=>dQ(s)?_Q(s,t):null),i=e.map(s=>s.usage?.total_tokens??null),r=e.map(s=>s.usage?.cost??null),o=new Set(e.map(s=>s.usage?.currency).filter(s=>s==="BRL"||s==="USD")),a=o.size===1?[...o][0]??null:null;return{run_count:e.length,duration_ms:km(n),total_tokens:km(i),cost:o.size<=1?{...km(r),currency:a}:{...km(e.map(()=>null)),currency:null}}}function dQ(e){return li(e,"phase")==="execution"&&li(e,"parent_run_id")===null}function km(e){let t=e.filter(n=>n!==null);return{value:t.length===0?null:t.reduce((n,i)=>n+i,0),known_runs:t.length,unknown_runs:e.length-t.length,coverage_ratio:e.length===0?1:t.length/e.length}}function _Q(e,t){let n=li(e,"started_at"),i=li(e,"finished_at");if(n===null)return null;let r=Date.parse(n),o=i===null?null:Date.parse(i),a=o===null&&e.status==="running"?t-r:(o??Number.NaN)-r;return Number.isFinite(a)?Math.max(0,a):null}function pS(e){return Object.keys(_S).map(t=>{let n=e.filter(r=>r.stage===t),i=n.flatMap(r=>[r.recorded_at,r.updated_at]).filter(r=>r!==null).sort(RM);return{stage:t,status:n.length===0?"pending":i.length===0?"missing_timestamp":"recorded",first_recorded_at:i.at(0)??null,last_recorded_at:i.at(-1)??null,document_count:n.length,test_count:n.filter(r=>r.kind==="test").length}})}function pQ(e,t){return t.has(e.id)||e.relations.some(n=>t.has(n))}function mQ(e){return e==="completed"?100:e==="verifying"?80:e==="executing"?50:e==="blocked"||e==="failed"||e==="cancelled"?0:10}function li(e,t){let n=e.data?.[t];return typeof n=="string"&&n.length>0?n:null}function ml(e,t){return e?.relations.find(n=>n.startsWith(t))??null}function TM(e,t){let n=e?.data?.source;if(typeof n!="object"||n===null)return null;let i=n[t];return typeof i=="string"&&i.length>0?i:null}var _S={definition:0,planning:1,execution:2,decisions:3,verification:4,evidence:5};function mS(e){return e.includes("/prds/")?{stage:"definition",kind:"prd"}:e.includes("/requirements/")?{stage:"definition",kind:"requirement"}:e.includes("/specs/")?{stage:"planning",kind:"spec"}:e.includes("/decisions/")?{stage:"decisions",kind:"decision"}:e.includes("/artifacts/evidence/")?{stage:"evidence",kind:"evidence"}:e.includes("/artifacts/tests/")?{stage:"verification",kind:"test"}:e.includes("/artifacts/evals/")?{stage:"verification",kind:"eval"}:e.includes("/artifacts/checks/")?{stage:"verification",kind:"check"}:e.includes("/tasks/")?{stage:"execution",kind:"task"}:e.includes("/executions/")?{stage:"execution",kind:"execution"}:e.includes("/runs/")?{stage:"execution",kind:"run"}:e.includes("/changes/")?{stage:"planning",kind:"change"}:{stage:"evidence",kind:"evidence"}}function wm(e){let t=[...e.matchAll(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})\b/g)].map(n=>n[0]).filter(n=>Number.isFinite(Date.parse(n))).sort(RM);return{recorded_at:t.at(0)??null,updated_at:t.at(-1)??null}}function RM(e,t){return Date.parse(e)-Date.parse(t)}function fQ(e){if(e.kind!=="change")return null;let t=e.content.match(/^## Decis(?:ões|oes)\s*\r?\n([\s\S]*?)(?=^##\s|\s*$)/m)?.[1]?.trim();return t===void 0||t.length===0||/^Nenhuma decis(?:ão|ao) registrada\.?$/i.test(t)?null:{id:(0,_s.createHash)("sha256").update(`${e.path}#decisions`).digest("hex").slice(0,16),path:`${e.path}#decisions`,title:`Decis\xF5es \u2014 ${e.title}`,stage:"decisions",kind:"decision",content:t,...wm(t)}}function gQ(e,t){return e.kind!=="evidence"||!e.content.includes(t)||!/(?:test|vitest|typecheck|biome|build|lint|check|eval)/i.test(e.content)||!/(?:passed|passing|aprovad[oa]|exit\s*code\s*[:=]?\s*0|\bPASS\b)/i.test(e.content)?null:{...e,id:(0,_s.createHash)("sha256").update(`${e.path}#verification`).digest("hex").slice(0,16),path:`${e.path}#verification`,title:`Verifica\xE7\xE3o \u2014 ${e.title}`,stage:"verification",kind:"check"}}function hQ(e,t){let n=e.data?.result;if(typeof n!="object"||n===null)return[];let i=n.evidence_ids;if(!Array.isArray(i))return[];let r=li(e,"finished_at");return i.filter(o=>typeof o=="string"&&o.length>0).filter(o=>!t.some(a=>a.kind==="evidence"&&a.content.includes(o))).map(o=>({id:(0,_s.createHash)("sha256").update(`${e.id}#evidence/${o}`).digest("hex").slice(0,16),path:`${vQ(e.id)}#evidence/${o}`,title:o,stage:"evidence",kind:"evidence",content:`Task: ${e.id}
|
|
2324
|
+
Evidence reference: ${o}`,recorded_at:r,updated_at:r}))}function yQ(e,t,n){let i=li(e,"finished_at");return[...t].filter(r=>!n.some(o=>o.content.includes(r))).sort().map(r=>({id:(0,_s.createHash)("sha256").update(`${e.id}#requirement/${r}`).digest("hex").slice(0,16),path:`.agents/requirements#${r}`,title:r,stage:"definition",kind:"requirement",content:`Task: ${e.id}
|
|
2325
|
+
Requirement reference: ${r}`,recorded_at:i,updated_at:i}))}function vQ(e){return`.agents/records/tasks/${e}.md`}function bQ(e,t){return t.match(/^#\s+(.+)$/m)?.[1]?.trim()??e.split("/").at(-1)??e}var OM=require("node:crypto");qe();async function CM(e,t,n){let i=await Ro(e,t,"task",n);if(i===null)throw new Error(`Canonical Task ${n} was not found`);let r={path:i,content:await e.readText(i)},o=f=>{let v=/^---\r?\n([\s\S]*?)\r?\n---/.exec(r.content)?.[1]??"",S=new RegExp(`^${f}:\\s*(.+?)\\s*$`,"m").exec(v)?.[1]?.trim();return S===void 0||S==="null"?null:S.replace(/^['"]|['"]$/g,"")};if(o("id")!==n)throw new Error(`Canonical Task identity mismatch: ${n}`);let a=(f,v)=>o(f)??new RegExp(`\\b${v}[A-Z0-9-]+`).exec(r.content)?.[0]??null,s=a("change_id","CHG-")??n,l=a("spec_id","SPEC-"),c=a("prd_id","PRD-"),u=[n,s,l,c].filter(f=>f!==null),d=e.canonicalTraceFiles(u,25e4).filter(f=>/\.(?:md|json|jsonl|txt|log)$/i.test(f.path)&&f.content.length<=25e4).map(f=>{let v=mS(f.path),S=wm(f.content);return{id:(0,OM.createHash)("sha256").update(f.path).digest("hex").slice(0,16),path:f.path,title:f.content.match(/^#\s+(.+)$/m)?.[1]?.trim()??f.path.split("/").at(-1)??f.path,...v,content:f.content,...S}}),_=pS(d),p=new Set(d.map(f=>f.stage)),g=o("risk"),m=o("status");return{schema_version:2,layout_version:t.version,readonly:!0,source:e.canonicalSource(),task_id:n,task_title:o("title")??r.content.match(/^#\s+(.+)$/m)?.[1]?.trim()??n,task_risk:g==="lite"||g==="standard"||g==="critical"?g:null,task_created_at:o("created_at"),task_progress:m==="completed"?100:m==="verifying"?80:m==="executing"?50:m==="blocked"||m==="failed"||m==="cancelled"?0:10,spec_id:l,prd_id:c,change_id:s,usage:e.taskTraceUsage(n),documents:d,stages:_,coverage:{stages_with_documents:p.size,stages_with_timestamps:_.filter(f=>f.status==="recorded").length,total_stages:6,evidence_count:d.filter(f=>f.kind==="evidence").length,test_count:d.filter(f=>f.kind==="test").length}}}function IM(e,t){let{filesystem:n,readLayout:i}=t;e.on(["GET","HEAD"],`${Se}/tasks/:id`,async r=>{try{let o=await i();return ye(r,await vb(n,o,r.req.param("id")))}catch(o){if(o instanceof Dt)throw o;return ye(r,{error:"Task not found"},404)}}),e.on(["GET","HEAD"],`${Se}/prds/:id`,async r=>{try{let o=await i();return ye(r,await bb(n,o,r.req.param("id")))}catch(o){if(o instanceof Dt)throw o;return ye(r,{error:"PRD not found"},404)}}),e.on(["GET","HEAD"],`${Se}/specs/:id`,async r=>{try{let o=await i();return ye(r,await Sb(n,o,r.req.param("id")))}catch(o){if(o instanceof Dt)throw o;return ye(r,{error:"SPEC not found"},404)}}),e.on(["GET","HEAD"],`${Se}/tasks/:id/trace`,async r=>{try{let o=await i(),a=r.req.param("id");return ye(r,n instanceof ct?await CM(n,o,a):await xM(n,o,a))}catch(o){if(o instanceof Dt)throw o;return ye(r,{error:"Task trace not found"},404)}})}var NM=require("node:crypto"),Em="127.0.0.1";function fS(e){try{let t=new URL(e);return t.protocol==="http:"&&(t.hostname===Em||t.hostname==="localhost")}catch{return!1}}function PM(e){try{let t=decodeURIComponent(e).replaceAll("\\","/");return!t.includes("\0")&&!t.split("/").some(n=>n==="..")}catch{return!1}}function gS(){return process.env.ZAIP_UI_TOKEN??(0,NM.randomBytes)(24).toString("base64url")}function $M(e){if(e.req.method!=="GET"&&e.req.method!=="HEAD"||e.req.path!=="/"&&e.req.path!=="/index.html")return!1;let t=e.req.header("origin");return t!==void 0&&!fS(t)?!1:e.req.header("sec-fetch-site")!=="cross-site"}var fl="zaip-dashboard-sqlite-runtime",LM="zaip-dashboard-sqlite-session",MM=5e3;function yS(e=process.env.ZAIP_WORKSPACE??process.cwd(),t=gS(),n=(0,gl.resolve)(process.env.ZAIP_UI_ROOT??"./dist"),i={}){let r=new Qh,o=x_(e,"runtime");o.log("runtime_app_started",{snapshot_read_only:i.snapshotReadOnly});let a=i.filesystem??new ei(e),s=a instanceof ct,l=s?Ai(a):null,c=async()=>i.layout??l??await Ai(a),u=i.snapshotReadOnly??s,d=i.snapshotState??"current",_=i.canonicalFilesystem??new ei(e),p=i.reconcileOpenWork??m$,g=i.refreshReadModel??(async()=>{s&&await hM(e,a)}),m=nm(e),f=(0,gl.resolve)(e),v=(0,gl.basename)(f),S=i.syncAgentAdapters??(()=>zO(e)),b=new Map,h=new Map,k=new Map,P=new Map,U=async(A,I,he=!1)=>{let me=k.get(A);if(!he&&me!==void 0&&(A.startsWith("operations:board:")||Date.now()-me.cachedAt<MM))return me.payload;let Le=P.get(A);if(Le!==void 0)return he?(await Le,U(A,I,!0)):Le;let Ce=I().then(Pe=>(k.set(A,{payload:Pe,cachedAt:Date.now()}),Pe)).finally(()=>P.delete(A));return P.set(A,Ce),Ce},$=A=>{let{from:I,to:he}=Et(A);return`${Jn(A)}:${I??""}:${he??""}`},B=()=>{h.clear(),k.clear(),P.clear()},z=null,R=QO(),L=null,J=null,le=!1,j=null,Q=!1,C=new Set,F=async(A=null)=>{if(A!==null&&C.add(A),ne.capturing)return ne.refresh();if(j!==null)return Q=!0,j;d="updating";let I=(0,jM.randomUUID)(),he=A;return o.log("projection_refresh_started",{refresh_id:I,job_id:he}),j=(async()=>{let me=0;do Q=!1,await g(),s&&(l=Ai(a)),B(),me+=1;while(Q&&me<2);d="current",R.clear(),o.log("projection_refresh_completed",{refresh_id:I,job_id:[...C][0]??he,job_ids:[...C],projection_updated_at:s?a.projectionUpdatedAt():null,latest_token_collected_at:s?a.latestTokenCollectedAt():null}),Q||C.clear()})().catch(me=>{throw R.record({trigger:"source_change",error:me}),o.log("projection_refresh_failed",{refresh_id:I,job_id:[...C][0]??he,job_ids:[...C],error:me}),C.clear(),me}).finally(()=>{j=null,Q&&(Q=!1,setTimeout(()=>{F().catch(Le=>R.record({trigger:"source_change",error:Le}))},250).unref())}),j},X=i.captureTelemetry??(s&&i.watchSources===!0&&process.env.ZAIP_DASHBOARD_WATCH_SOURCES!=="0"?()=>MO(e):void 0),ne=AM({refresh:F,...X===void 0?{}:{capture:async()=>(j!==null&&await j.catch(()=>{}),X())},onCaptureSuccess:A=>{J=A,L=null,le=A.catch_up_complete===!1},onCaptureFailure:A=>{L=EO(A),o.log("active_telemetry_capture_failed",L)}}),ve=()=>ne.pending||L!==null||le?"updating":d;wM({workspaceRoot:e,discoverSourceRoots:()=>hc(e),staleSeed:s&&d==="updating",watchSources:s&&i.watchSources===!0,refresh:F,synchronizeTelemetry:ne.refresh,onRefreshFailure:R.record});let ge=dM({diagnostics:o,reconcile:(A,I)=>p(_,e,{hostTerminalOnly:A==="host-terminal",jobId:I}),snapshotTimes:()=>({projection_updated_at:s?a.projectionUpdatedAt():null,latest_token_collected_at:s?a.latestTokenCollectedAt():null}),refresh:A=>F(A)}),q=A=>{let I=$(A),he=h.get(I);if(he!==void 0&&Date.now()-he.cachedAt<MM)return A.header("X-ZAIP-Snapshot-Cache","hit"),Promise.resolve(he.snapshot);let me=b.get(I);if(me!==void 0)return A.header("X-ZAIP-Snapshot-Cache","inflight"),me;A.header("X-ZAIP-Snapshot-Cache","miss");let Le=c().then(Ce=>WL(a,e,A,Ce)).then(Ce=>(h.set(I,{snapshot:Ce,cachedAt:Date.now()}),Ce)).finally(()=>{b.delete(I)});return b.set(I,Le),Le};return r.use("*",async(A,I)=>pM(A.req.url,A.req.header("host"))?(A.header("Cache-Control","no-store"),A.header("X-Content-Type-Options","nosniff"),A.header("Referrer-Policy","no-referrer"),A.header("Content-Security-Policy","default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; object-src 'none'; frame-ancestors 'none'"),$M(A)&&kO(A,LM,t,{httpOnly:!0,path:"/",sameSite:"Strict"}),I()):A.json({error:"Host rejected"},403)),r.use(`${Se}/*`,async(A,I)=>{let he=A.req.method==="PUT"&&(A.req.path===`${Se}/work-priority`||A.req.path===`${Se}/project-settings`||!u&&(A.req.path===`${Se}/pricing`||A.req.path===`${Se}/fx-rate`||A.req.path===`${Se}/agent-catalog`)),me=A.req.method==="POST"&&A.req.path===`${Se}/reconcile-open-work`,Le=A.req.method==="GET"&&A.req.path===`${Se}/browser-lease`,Ce=A.req.method==="POST"&&(A.req.path===`${Se}/refresh-projection`||A.req.path===`${Se}/capture-telemetry`);if(A.req.method!=="GET"&&A.req.method!=="HEAD"&&!he&&!me&&!Ce&&!Le)return A.header("Allow",A.req.path===`${Se}/pricing`||A.req.path===`${Se}/fx-rate`||A.req.path===`${Se}/agent-catalog`||A.req.path===`${Se}/project-settings`||A.req.path===`${Se}/work-priority`?"GET, HEAD, PUT":A.req.path===`${Se}/reconcile-open-work`||A.req.path===`${Se}/refresh-projection`||A.req.path===`${Se}/capture-telemetry`?"POST":"GET, HEAD"),A.json({error:"Dashboard API is read-only"},405);if(A.req.path===`${Se}/health`||A.req.path===`${Se}/ready`)return I();let Pe=A.req.header("origin");if(Pe!==void 0&&!fS(Pe))return A.json({error:"Origin rejected"},403);let rn=A.req.header("x-zaip-session"),Y=SO(A,LM),ce=A.req.method==="GET"&&A.req.path.startsWith(`${Se}/agent-catalog-assets/`)?A.req.query("token"):void 0,$e=Le?A.req.query("token"):void 0;return Le&&$e!==t?A.json({error:"Invalid local session"},401):rn!==t&&Y!==t&&ce!==t&&$e!==t?A.json({error:"Invalid local session"},401):I()}),pC(r,Se,i.launcherOwned===!0),r.on(["GET","HEAD"],`${Se}/health`,async A=>{try{let[I,he]=await Promise.all([c(),fc(_)]);return ye(A,{kind:fl,workspaceKey:m,workspace:f,workspace_name:v,server_pid:process.pid,service:"zaip-aios-dashboard",status:he==="initialized"&&L===null&&!le?R.healthStatus:"degraded",api_version:2,workspace_layout:I.version,lifecycle_manifest_state:he,read_only:!0,storage:s?a.metadata():{storage_mode:"filesystem"},snapshot_state:ve(),projection_refresh_failure:R.failure,active_capture_failure:L,active_capture:J})}catch(I){return ye(A,{kind:fl,workspaceKey:m,workspace:f,workspace_name:v,server_pid:process.pid,service:"zaip-aios-dashboard",status:"unavailable",api_version:2,read_only:!0,error:I instanceof Error?I.message:String(I)},503)}}),r.on(["GET","HEAD"],`${Se}/ready`,async A=>{try{let[I,he]=await Promise.all([c(),fc(_)]),me=he==="initialized"&&L===null&&!le?"ready":"degraded";if(s){let Ce=bM(e);z!==null&&z!==Ce&&(a.refresh(),B(),l=Ai(a)),z=Ce;let Pe=a.metadata();return ye(A,{kind:fl,workspaceKey:m,workspace:f,workspace_name:v,server_pid:process.pid,status:me,workspace_layout:I.version,lifecycle_manifest_state:he,storage_mode:Pe.storage_mode,activity_count:Pe.activity_count,day_count:Pe.daily_aggregate_count,snapshot_state:ve(),projection_refresh_failure:R.failure,active_capture_failure:L,active_capture:J,snapshot_revision:Ce,projection_updated_at:a.projectionUpdatedAt(),latest_token_collected_at:a.latestTokenCollectedAt()})}let Le=await po(a,I,{from:null,to:null});return ye(A,{kind:fl,workspaceKey:m,workspace:f,workspace_name:v,server_pid:process.pid,status:me,lifecycle_manifest_state:he,source_latest_at:Le.summary.source_latest_at,active_capture:J})}catch(I){return ye(A,{kind:fl,workspaceKey:m,status:"unavailable",error:I instanceof Error?I.message:String(I)},503)}}),r.on(["GET","HEAD"],`${Se}/dashboard-identity`,async A=>ye(A,await tm(a,e))),sM(r,{filesystem:a,canonicalFilesystem:_,isSqliteSnapshot:s,readLayout:c,readSnapshot:q,readAggregate:U,clearSnapshotCache:B}),_M(r,{readLayout:c,diagnostics:o,reconcileWork:ge,refresh:A=>F(A),snapshotState:ve,refreshCompleted:()=>ve()==="current"&&j===null}),r.post(`${Se}/refresh-projection`,async A=>{try{return await c(),await ne.refresh(!0),L!==null?A.json({error:"Telemetry capture is unavailable",snapshot_state:ve(),active_capture_failure:L},503):A.json(await q(A))}catch(I){if(I instanceof Dt)throw I;return A.json({error:I instanceof Error?I.message:String(I)},400)}}),r.post(`${Se}/capture-telemetry`,async A=>(await c(),ne.refresh().catch(I=>R.record({trigger:"source_change",error:I})),A.json({snapshot_state:ve()},202))),BL(r,{filesystem:a,canonicalFilesystem:_,isSqliteSnapshot:s,readLayout:c,readSnapshot:q,readAggregate:U,clearSnapshotCache:B}),mM(r,a,B),dC(r,{filesystem:a,workspaceRoot:e,syncAgentAdapters:S,clearSnapshotCache:B}),r.on(["GET","HEAD"],`${Se}/project-settings`,async A=>{try{return ye(A,await bc(_))}catch(I){return ye(A,{error:I instanceof Error?I.message:String(I)},400)}}),r.on(["GET","HEAD"],`${Se}/project-settings/overview`,async A=>ye(A,await XO(_))),r.put(`${Se}/project-settings`,async A=>{try{let I=await YO(_,await A.req.json());return B(),A.json(I)}catch(I){return A.json({error:I instanceof Error?I.message:"Project settings update failed"},400)}}),IM(r,{filesystem:a,canonicalFilesystem:_,isSqliteSnapshot:s,readLayout:c,readSnapshot:q,readAggregate:U,clearSnapshotCache:B}),r.onError((A,I)=>{let he=A instanceof Dt?409:500;return ye(I,{error:he===409?A.message:"Dashboard projection failed"},he)}),r.all(`${Se}/*`,A=>ye(A,{error:"Not found"},404)),r.on(["GET","HEAD"],"/",Al({path:`${n}/index.html`})),r.use("/*",async(A,I)=>PM(A.req.path)?I():A.json({error:"Invalid dashboard asset path"},400)),r.use("/*",Al({root:n})),r.on(["GET","HEAD"],"/*",Al({path:`${n}/index.html`})),r}var Am=performance.now(),UM=gS(),Tm=process.env.ZAIP_WORKSPACE??process.cwd(),DM;function hS(){return DM??=yS(Tm,UM),DM}var SQ=new Proxy({},{get(e,t){let n=Reflect.get(hS(),t);return typeof n=="function"?n.bind(hS()):n}});async function kQ(){let e=Number.parseInt(process.env.ZAIP_SERVER_PORT??"4317",10);pl(Am,"main_entered");let t=performance.now(),i=await _l(Tm,{forceCanonical:!1,preferExisting:!0});EM(t,i),pl(Am,"read_model_ready");let r=yS(Tm,UM,void 0,{filesystem:new ct(Tm),snapshotState:i.cache==="stale_seed"?"updating":"current",watchSources:!0,launcherOwned:!0});pl(Am,"runtime_app_ready"),WS({fetch:r.fetch,hostname:Em,port:e},({port:o})=>{pl(Am,"listening"),process.stdout.write(`ZAIP-AIOS dashboard API: http://${Em}:${o}${Se}/health
|
|
2326
|
+
`)})}(process.argv[1]?.endsWith("server.cjs")||process.argv[1]?.endsWith("server.js")||process.argv[1]?.endsWith("server.mjs"))&&kQ();0&&(module.exports={SqliteReadModelFileSystem,app,createDashboardApp,dashboardWorkspaceKey,defaultDashboardApp,githubRepositoryFromRemote,manifestRun,mergeManifestRuns,openWorkIds,projectAllTimeTopTasks,projectionPeriodFilter,rebuildSqliteReadModel,reconciliationNeedsRefresh,reconciliationResult,validateSqliteReadModelSchema});
|
|
2327
2327
|
//# sourceMappingURL=server.cjs.map
|