pi-crew 0.1.37 → 0.1.39
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/AGENTS.md +1 -1
- package/CHANGELOG.md +27 -0
- package/README.md +5 -0
- package/agents/analyst.md +11 -11
- package/agents/critic.md +11 -11
- package/agents/executor.md +11 -11
- package/agents/explorer.md +11 -11
- package/agents/planner.md +11 -11
- package/agents/reviewer.md +11 -11
- package/agents/security-reviewer.md +11 -11
- package/agents/test-engineer.md +11 -11
- package/agents/verifier.md +11 -11
- package/agents/writer.md +11 -11
- package/docs/refactor-tasks-phase3.md +394 -394
- package/docs/refactor-tasks-phase4.md +564 -564
- package/docs/refactor-tasks-phase5.md +402 -402
- package/docs/refactor-tasks-phase6.md +662 -662
- package/docs/research-extension-examples.md +297 -297
- package/docs/research-extension-system.md +324 -324
- package/docs/research-optimization-plan.md +548 -548
- package/docs/research-pi-coding-agent.md +357 -357
- package/docs/research-source-pi-crew-reference.md +174 -174
- package/docs/resource-formats.md +10 -8
- package/docs/runtime-flow.md +148 -148
- package/docs/source-runtime-refactor-map.md +83 -83
- package/docs/usage.md +6 -0
- package/index.ts +6 -6
- package/package.json +3 -3
- package/schema.json +2 -2
- package/src/agents/agent-serializer.ts +34 -34
- package/src/config/config.ts +8 -4
- package/src/extension/cross-extension-rpc.ts +82 -82
- package/src/extension/import-index.ts +18 -2
- package/src/extension/register.ts +11 -1
- package/src/extension/registration/compaction-guard.ts +125 -125
- package/src/extension/registration/subagent-helpers.ts +30 -6
- package/src/extension/registration/subagent-tools.ts +8 -3
- package/src/extension/result-watcher.ts +98 -98
- package/src/extension/run-import.ts +12 -2
- package/src/extension/run-index.ts +12 -2
- package/src/extension/run-maintenance.ts +24 -24
- package/src/extension/team-tool/api.ts +54 -14
- package/src/extension/team-tool/cancel.ts +31 -31
- package/src/extension/team-tool/doctor.ts +179 -179
- package/src/extension/team-tool/inspect.ts +41 -41
- package/src/extension/team-tool/lifecycle-actions.ts +79 -79
- package/src/extension/team-tool/plan.ts +19 -19
- package/src/extension/team-tool/status.ts +73 -73
- package/src/observability/correlation.ts +35 -35
- package/src/observability/event-to-metric.ts +54 -54
- package/src/observability/exporters/adapter.ts +24 -24
- package/src/observability/exporters/otlp-exporter.ts +65 -65
- package/src/observability/exporters/prometheus-exporter.ts +47 -47
- package/src/observability/metric-registry.ts +72 -72
- package/src/observability/metric-retention.ts +46 -46
- package/src/observability/metric-sink.ts +51 -51
- package/src/observability/metrics-primitives.ts +166 -166
- package/src/prompt/prompt-runtime.ts +68 -68
- package/src/runtime/agent-control.ts +64 -64
- package/src/runtime/agent-memory.ts +72 -72
- package/src/runtime/agent-observability.ts +114 -113
- package/src/runtime/async-marker.ts +26 -26
- package/src/runtime/background-runner.ts +53 -53
- package/src/runtime/crash-recovery.ts +56 -56
- package/src/runtime/crew-agent-records.ts +54 -9
- package/src/runtime/crew-agent-runtime.ts +58 -58
- package/src/runtime/deadletter.ts +36 -36
- package/src/runtime/direct-run.ts +35 -35
- package/src/runtime/foreground-control.ts +82 -82
- package/src/runtime/green-contract.ts +46 -46
- package/src/runtime/group-join.ts +88 -88
- package/src/runtime/heartbeat-gradient.ts +28 -28
- package/src/runtime/heartbeat-watcher.ts +80 -80
- package/src/runtime/live-agent-control.ts +87 -78
- package/src/runtime/live-agent-manager.ts +85 -85
- package/src/runtime/live-control-realtime.ts +36 -36
- package/src/runtime/live-session-runtime.ts +299 -299
- package/src/runtime/manifest-cache.ts +248 -212
- package/src/runtime/model-fallback.ts +261 -261
- package/src/runtime/parallel-research.ts +44 -44
- package/src/runtime/parallel-utils.ts +99 -99
- package/src/runtime/pi-json-output.ts +111 -111
- package/src/runtime/policy-engine.ts +78 -78
- package/src/runtime/post-exit-stdio-guard.ts +86 -86
- package/src/runtime/process-status.ts +56 -56
- package/src/runtime/progress-event-coalescer.ts +43 -43
- package/src/runtime/recovery-recipes.ts +74 -74
- package/src/runtime/retry-executor.ts +59 -59
- package/src/runtime/role-permission.ts +39 -39
- package/src/runtime/session-usage.ts +79 -79
- package/src/runtime/sidechain-output.ts +28 -28
- package/src/runtime/subagent-manager.ts +80 -12
- package/src/runtime/task-display.ts +38 -38
- package/src/runtime/task-output-context.ts +127 -106
- package/src/runtime/task-runner/live-executor.ts +98 -98
- package/src/runtime/task-runner/progress.ts +111 -111
- package/src/runtime/task-runner/result-utils.ts +14 -14
- package/src/runtime/task-runner/state-helpers.ts +22 -22
- package/src/runtime/team-runner.ts +1 -1
- package/src/runtime/worker-heartbeat.ts +21 -21
- package/src/runtime/worker-startup.ts +57 -57
- package/src/schema/config-schema.ts +21 -21
- package/src/schema/team-tool-schema.ts +100 -100
- package/src/state/artifact-store.ts +122 -108
- package/src/state/contracts.ts +105 -105
- package/src/state/jsonl-writer.ts +77 -77
- package/src/state/mailbox.ts +67 -22
- package/src/state/state-store.ts +36 -5
- package/src/state/task-claims.ts +42 -42
- package/src/state/usage.ts +29 -29
- package/src/subagents/async-entry.ts +1 -1
- package/src/subagents/index.ts +3 -3
- package/src/subagents/live/control.ts +1 -1
- package/src/subagents/live/manager.ts +1 -1
- package/src/subagents/live/realtime.ts +1 -1
- package/src/subagents/live/session-runtime.ts +1 -1
- package/src/subagents/manager.ts +1 -1
- package/src/subagents/spawn.ts +1 -1
- package/src/teams/discover-teams.ts +27 -5
- package/src/teams/team-serializer.ts +38 -36
- package/src/types/diff.d.ts +18 -18
- package/src/ui/crew-footer.ts +101 -101
- package/src/ui/crew-select-list.ts +111 -111
- package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
- package/src/ui/dynamic-border.ts +25 -25
- package/src/ui/layout-primitives.ts +106 -106
- package/src/ui/loaders.ts +158 -158
- package/src/ui/mascot.ts +441 -441
- package/src/ui/render-diff.ts +119 -119
- package/src/ui/run-dashboard.ts +5 -2
- package/src/ui/run-snapshot-cache.ts +19 -8
- package/src/ui/spinner.ts +17 -17
- package/src/ui/status-colors.ts +54 -54
- package/src/ui/syntax-highlight.ts +116 -116
- package/src/ui/transcript-viewer.ts +15 -1
- package/src/utils/completion-dedupe.ts +63 -63
- package/src/utils/file-coalescer.ts +84 -84
- package/src/utils/frontmatter.ts +36 -36
- package/src/utils/fs-watch.ts +31 -31
- package/src/utils/git.ts +262 -262
- package/src/utils/ids.ts +12 -12
- package/src/utils/names.ts +26 -26
- package/src/utils/paths.ts +3 -2
- package/src/utils/safe-paths.ts +34 -0
- package/src/utils/sleep.ts +32 -32
- package/src/utils/timings.ts +31 -31
- package/src/utils/visual.ts +159 -159
- package/src/workflows/discover-workflows.ts +30 -3
- package/src/workflows/validate-workflow.ts +40 -40
- package/src/worktree/branch-freshness.ts +45 -45
- package/teams/default.team.md +12 -12
- package/teams/fast-fix.team.md +11 -11
- package/teams/implementation.team.md +18 -18
- package/teams/parallel-research.team.md +14 -14
- package/teams/research.team.md +11 -11
- package/teams/review.team.md +12 -12
- package/workflows/default.workflow.md +29 -29
- package/workflows/fast-fix.workflow.md +22 -22
- package/workflows/implementation.workflow.md +38 -38
- package/workflows/parallel-research.workflow.md +46 -46
- package/workflows/research.workflow.md +22 -22
- package/workflows/review.workflow.md +30 -30
|
@@ -1,47 +1,47 @@
|
|
|
1
|
-
import type { HistogramPoint, MetricLabels, MetricPoint, MetricSnapshot } from "../metrics-primitives.ts";
|
|
2
|
-
|
|
3
|
-
function prometheusName(name: string): string {
|
|
4
|
-
return name.replace(/\./g, "_");
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
function escapeLabel(value: string): string {
|
|
8
|
-
return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/"/g, "\\\"");
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
function labelsText(labels: MetricLabels): string {
|
|
12
|
-
const entries = Object.entries(labels);
|
|
13
|
-
if (!entries.length) return "";
|
|
14
|
-
return `{${entries.map(([key, value]) => `${key}="${escapeLabel(String(value))}"`).join(",")}}`;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function metricType(type: MetricSnapshot["type"]): string {
|
|
18
|
-
return type === "histogram" ? "histogram" : type === "gauge" ? "gauge" : "counter";
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function isHistogramPoint(value: MetricPoint | HistogramPoint): value is HistogramPoint {
|
|
22
|
-
return "buckets" in value && "counts" in value;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export function formatPrometheus(snapshots: MetricSnapshot[]): string {
|
|
26
|
-
const lines: string[] = [];
|
|
27
|
-
for (const snapshot of snapshots) {
|
|
28
|
-
const name = prometheusName(snapshot.name);
|
|
29
|
-
lines.push(`# HELP ${name} ${snapshot.description}`);
|
|
30
|
-
lines.push(`# TYPE ${name} ${metricType(snapshot.type)}`);
|
|
31
|
-
for (const value of snapshot.values) {
|
|
32
|
-
if (isHistogramPoint(value)) {
|
|
33
|
-
let cumulative = 0;
|
|
34
|
-
for (let index = 0; index < value.buckets.length; index += 1) {
|
|
35
|
-
cumulative += value.counts[index] ?? 0;
|
|
36
|
-
const le = Number.isFinite(value.buckets[index]) ? String(value.buckets[index]) : "+Inf";
|
|
37
|
-
lines.push(`${name}_bucket${labelsText({ ...value.labels, le })} ${cumulative}`);
|
|
38
|
-
}
|
|
39
|
-
lines.push(`${name}_sum${labelsText(value.labels)} ${value.sum}`);
|
|
40
|
-
lines.push(`${name}_count${labelsText(value.labels)} ${value.count}`);
|
|
41
|
-
} else {
|
|
42
|
-
lines.push(`${name}${labelsText(value.labels)} ${value.value}`);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return `${lines.join("\n")}\n`;
|
|
47
|
-
}
|
|
1
|
+
import type { HistogramPoint, MetricLabels, MetricPoint, MetricSnapshot } from "../metrics-primitives.ts";
|
|
2
|
+
|
|
3
|
+
function prometheusName(name: string): string {
|
|
4
|
+
return name.replace(/\./g, "_");
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function escapeLabel(value: string): string {
|
|
8
|
+
return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/"/g, "\\\"");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function labelsText(labels: MetricLabels): string {
|
|
12
|
+
const entries = Object.entries(labels);
|
|
13
|
+
if (!entries.length) return "";
|
|
14
|
+
return `{${entries.map(([key, value]) => `${key}="${escapeLabel(String(value))}"`).join(",")}}`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function metricType(type: MetricSnapshot["type"]): string {
|
|
18
|
+
return type === "histogram" ? "histogram" : type === "gauge" ? "gauge" : "counter";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function isHistogramPoint(value: MetricPoint | HistogramPoint): value is HistogramPoint {
|
|
22
|
+
return "buckets" in value && "counts" in value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function formatPrometheus(snapshots: MetricSnapshot[]): string {
|
|
26
|
+
const lines: string[] = [];
|
|
27
|
+
for (const snapshot of snapshots) {
|
|
28
|
+
const name = prometheusName(snapshot.name);
|
|
29
|
+
lines.push(`# HELP ${name} ${snapshot.description}`);
|
|
30
|
+
lines.push(`# TYPE ${name} ${metricType(snapshot.type)}`);
|
|
31
|
+
for (const value of snapshot.values) {
|
|
32
|
+
if (isHistogramPoint(value)) {
|
|
33
|
+
let cumulative = 0;
|
|
34
|
+
for (let index = 0; index < value.buckets.length; index += 1) {
|
|
35
|
+
cumulative += value.counts[index] ?? 0;
|
|
36
|
+
const le = Number.isFinite(value.buckets[index]) ? String(value.buckets[index]) : "+Inf";
|
|
37
|
+
lines.push(`${name}_bucket${labelsText({ ...value.labels, le })} ${cumulative}`);
|
|
38
|
+
}
|
|
39
|
+
lines.push(`${name}_sum${labelsText(value.labels)} ${value.sum}`);
|
|
40
|
+
lines.push(`${name}_count${labelsText(value.labels)} ${value.count}`);
|
|
41
|
+
} else {
|
|
42
|
+
lines.push(`${name}${labelsText(value.labels)} ${value.value}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return `${lines.join("\n")}\n`;
|
|
47
|
+
}
|
|
@@ -1,72 +1,72 @@
|
|
|
1
|
-
import { Counter, Gauge, Histogram, type Metric, type MetricSnapshot } from "./metrics-primitives.ts";
|
|
2
|
-
|
|
3
|
-
const METRIC_NAME_PATTERN = /^crew\.[a-z]+\.[a-z][a-z_]*$/;
|
|
4
|
-
|
|
5
|
-
function assertMetricName(name: string): void {
|
|
6
|
-
if (!METRIC_NAME_PATTERN.test(name)) throw new Error(`Invalid metric name '${name}'. Expected crew.<domain>.<measure>.`);
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export class MetricRegistry {
|
|
10
|
-
private metrics = new Map<string, Metric>();
|
|
11
|
-
|
|
12
|
-
registerCounter(name: string, description: string): Counter {
|
|
13
|
-
assertMetricName(name);
|
|
14
|
-
if (this.metrics.has(name)) throw new Error(`Metric '${name}' is already registered.`);
|
|
15
|
-
const metric = new Counter(name, description);
|
|
16
|
-
this.metrics.set(name, metric);
|
|
17
|
-
return metric;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
registerGauge(name: string, description: string): Gauge {
|
|
21
|
-
assertMetricName(name);
|
|
22
|
-
if (this.metrics.has(name)) throw new Error(`Metric '${name}' is already registered.`);
|
|
23
|
-
const metric = new Gauge(name, description);
|
|
24
|
-
this.metrics.set(name, metric);
|
|
25
|
-
return metric;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
registerHistogram(name: string, description: string, buckets?: number[]): Histogram {
|
|
29
|
-
assertMetricName(name);
|
|
30
|
-
if (this.metrics.has(name)) throw new Error(`Metric '${name}' is already registered.`);
|
|
31
|
-
const metric = new Histogram(name, description, buckets);
|
|
32
|
-
this.metrics.set(name, metric);
|
|
33
|
-
return metric;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
counter(name: string, description: string): Counter {
|
|
37
|
-
const existing = this.metrics.get(name);
|
|
38
|
-
if (existing instanceof Counter) return existing;
|
|
39
|
-
if (existing) throw new Error(`Metric '${name}' is not a counter.`);
|
|
40
|
-
return this.registerCounter(name, description);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
gauge(name: string, description: string): Gauge {
|
|
44
|
-
const existing = this.metrics.get(name);
|
|
45
|
-
if (existing instanceof Gauge) return existing;
|
|
46
|
-
if (existing) throw new Error(`Metric '${name}' is not a gauge.`);
|
|
47
|
-
return this.registerGauge(name, description);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
histogram(name: string, description: string, buckets?: number[]): Histogram {
|
|
51
|
-
const existing = this.metrics.get(name);
|
|
52
|
-
if (existing instanceof Histogram) return existing;
|
|
53
|
-
if (existing) throw new Error(`Metric '${name}' is not a histogram.`);
|
|
54
|
-
return this.registerHistogram(name, description, buckets);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
get(name: string): Metric | undefined {
|
|
58
|
-
return this.metrics.get(name);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
snapshot(): MetricSnapshot[] {
|
|
62
|
-
return [...this.metrics.values()].map((metric) => metric.snapshot());
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
dispose(): void {
|
|
66
|
-
this.metrics.clear();
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function createMetricRegistry(): MetricRegistry {
|
|
71
|
-
return new MetricRegistry();
|
|
72
|
-
}
|
|
1
|
+
import { Counter, Gauge, Histogram, type Metric, type MetricSnapshot } from "./metrics-primitives.ts";
|
|
2
|
+
|
|
3
|
+
const METRIC_NAME_PATTERN = /^crew\.[a-z]+\.[a-z][a-z_]*$/;
|
|
4
|
+
|
|
5
|
+
function assertMetricName(name: string): void {
|
|
6
|
+
if (!METRIC_NAME_PATTERN.test(name)) throw new Error(`Invalid metric name '${name}'. Expected crew.<domain>.<measure>.`);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class MetricRegistry {
|
|
10
|
+
private metrics = new Map<string, Metric>();
|
|
11
|
+
|
|
12
|
+
registerCounter(name: string, description: string): Counter {
|
|
13
|
+
assertMetricName(name);
|
|
14
|
+
if (this.metrics.has(name)) throw new Error(`Metric '${name}' is already registered.`);
|
|
15
|
+
const metric = new Counter(name, description);
|
|
16
|
+
this.metrics.set(name, metric);
|
|
17
|
+
return metric;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
registerGauge(name: string, description: string): Gauge {
|
|
21
|
+
assertMetricName(name);
|
|
22
|
+
if (this.metrics.has(name)) throw new Error(`Metric '${name}' is already registered.`);
|
|
23
|
+
const metric = new Gauge(name, description);
|
|
24
|
+
this.metrics.set(name, metric);
|
|
25
|
+
return metric;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
registerHistogram(name: string, description: string, buckets?: number[]): Histogram {
|
|
29
|
+
assertMetricName(name);
|
|
30
|
+
if (this.metrics.has(name)) throw new Error(`Metric '${name}' is already registered.`);
|
|
31
|
+
const metric = new Histogram(name, description, buckets);
|
|
32
|
+
this.metrics.set(name, metric);
|
|
33
|
+
return metric;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
counter(name: string, description: string): Counter {
|
|
37
|
+
const existing = this.metrics.get(name);
|
|
38
|
+
if (existing instanceof Counter) return existing;
|
|
39
|
+
if (existing) throw new Error(`Metric '${name}' is not a counter.`);
|
|
40
|
+
return this.registerCounter(name, description);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
gauge(name: string, description: string): Gauge {
|
|
44
|
+
const existing = this.metrics.get(name);
|
|
45
|
+
if (existing instanceof Gauge) return existing;
|
|
46
|
+
if (existing) throw new Error(`Metric '${name}' is not a gauge.`);
|
|
47
|
+
return this.registerGauge(name, description);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
histogram(name: string, description: string, buckets?: number[]): Histogram {
|
|
51
|
+
const existing = this.metrics.get(name);
|
|
52
|
+
if (existing instanceof Histogram) return existing;
|
|
53
|
+
if (existing) throw new Error(`Metric '${name}' is not a histogram.`);
|
|
54
|
+
return this.registerHistogram(name, description, buckets);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
get(name: string): Metric | undefined {
|
|
58
|
+
return this.metrics.get(name);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
snapshot(): MetricSnapshot[] {
|
|
62
|
+
return [...this.metrics.values()].map((metric) => metric.snapshot());
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
dispose(): void {
|
|
66
|
+
this.metrics.clear();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function createMetricRegistry(): MetricRegistry {
|
|
71
|
+
return new MetricRegistry();
|
|
72
|
+
}
|
|
@@ -1,46 +1,46 @@
|
|
|
1
|
-
import { labelKey, type MetricLabels } from "./metrics-primitives.ts";
|
|
2
|
-
|
|
3
|
-
interface WindowEvent {
|
|
4
|
-
timestamp: number;
|
|
5
|
-
labels: MetricLabels;
|
|
6
|
-
delta: number;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export class TimeWindowedCounter {
|
|
10
|
-
private events: WindowEvent[] = [];
|
|
11
|
-
private readonly windowMs: number;
|
|
12
|
-
private readonly now: () => number;
|
|
13
|
-
|
|
14
|
-
constructor(windowMs = 3_600_000, now: () => number = () => Date.now()) {
|
|
15
|
-
this.windowMs = windowMs;
|
|
16
|
-
this.now = now;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
inc(labels: MetricLabels = {}, delta = 1): void {
|
|
20
|
-
if (!Number.isFinite(delta)) return;
|
|
21
|
-
this.events.push({ timestamp: this.now(), labels: { ...labels }, delta });
|
|
22
|
-
this.prune();
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
count(labels: MetricLabels = {}, durationMs = this.windowMs): number {
|
|
26
|
-
this.prune();
|
|
27
|
-
const key = labelKey(labels);
|
|
28
|
-
const cutoff = this.now() - durationMs;
|
|
29
|
-
return this.events.filter((event) => event.timestamp >= cutoff && labelKey(event.labels) === key).reduce((sum, event) => sum + event.delta, 0);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
rate(labels: MetricLabels = {}, durationMs = this.windowMs): number {
|
|
33
|
-
if (durationMs <= 0) return 0;
|
|
34
|
-
return this.count(labels, durationMs) / (durationMs / 1000);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
size(): number {
|
|
38
|
-
this.prune();
|
|
39
|
-
return this.events.length;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
private prune(): void {
|
|
43
|
-
const cutoff = this.now() - this.windowMs;
|
|
44
|
-
this.events = this.events.filter((event) => event.timestamp >= cutoff);
|
|
45
|
-
}
|
|
46
|
-
}
|
|
1
|
+
import { labelKey, type MetricLabels } from "./metrics-primitives.ts";
|
|
2
|
+
|
|
3
|
+
interface WindowEvent {
|
|
4
|
+
timestamp: number;
|
|
5
|
+
labels: MetricLabels;
|
|
6
|
+
delta: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class TimeWindowedCounter {
|
|
10
|
+
private events: WindowEvent[] = [];
|
|
11
|
+
private readonly windowMs: number;
|
|
12
|
+
private readonly now: () => number;
|
|
13
|
+
|
|
14
|
+
constructor(windowMs = 3_600_000, now: () => number = () => Date.now()) {
|
|
15
|
+
this.windowMs = windowMs;
|
|
16
|
+
this.now = now;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
inc(labels: MetricLabels = {}, delta = 1): void {
|
|
20
|
+
if (!Number.isFinite(delta)) return;
|
|
21
|
+
this.events.push({ timestamp: this.now(), labels: { ...labels }, delta });
|
|
22
|
+
this.prune();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
count(labels: MetricLabels = {}, durationMs = this.windowMs): number {
|
|
26
|
+
this.prune();
|
|
27
|
+
const key = labelKey(labels);
|
|
28
|
+
const cutoff = this.now() - durationMs;
|
|
29
|
+
return this.events.filter((event) => event.timestamp >= cutoff && labelKey(event.labels) === key).reduce((sum, event) => sum + event.delta, 0);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
rate(labels: MetricLabels = {}, durationMs = this.windowMs): number {
|
|
33
|
+
if (durationMs <= 0) return 0;
|
|
34
|
+
return this.count(labels, durationMs) / (durationMs / 1000);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
size(): number {
|
|
38
|
+
this.prune();
|
|
39
|
+
return this.events.length;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private prune(): void {
|
|
43
|
+
const cutoff = this.now() - this.windowMs;
|
|
44
|
+
this.events = this.events.filter((event) => event.timestamp >= cutoff);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
import * as fs from "node:fs";
|
|
2
|
-
import * as path from "node:path";
|
|
3
|
-
import { redactSecrets } from "../runtime/diagnostic-export.ts";
|
|
4
|
-
import { logInternalError } from "../utils/internal-error.ts";
|
|
5
|
-
import type { MetricRegistry } from "./metric-registry.ts";
|
|
6
|
-
import type { MetricSnapshot } from "./metrics-primitives.ts";
|
|
7
|
-
|
|
8
|
-
export interface MetricSink {
|
|
9
|
-
writeSnapshot(snapshots: MetricSnapshot[]): void;
|
|
10
|
-
dispose(): void;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export interface MetricFileSinkOptions {
|
|
14
|
-
crewRoot: string;
|
|
15
|
-
registry: MetricRegistry;
|
|
16
|
-
retentionDays?: number;
|
|
17
|
-
intervalMs?: number;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function rotateOldFiles(dir: string, retentionDays: number, now = Date.now()): void {
|
|
21
|
-
if (!fs.existsSync(dir)) return;
|
|
22
|
-
const maxAge = retentionDays * 24 * 60 * 60 * 1000;
|
|
23
|
-
for (const file of fs.readdirSync(dir)) {
|
|
24
|
-
if (!file.endsWith(".jsonl")) continue;
|
|
25
|
-
const fullPath = path.join(dir, file);
|
|
26
|
-
try {
|
|
27
|
-
if (now - fs.statSync(fullPath).mtimeMs > maxAge) fs.unlinkSync(fullPath);
|
|
28
|
-
} catch (error) {
|
|
29
|
-
logInternalError("metric-sink.rotate", error, fullPath);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function createMetricFileSink(opts: MetricFileSinkOptions): MetricSink {
|
|
35
|
-
const dir = path.join(opts.crewRoot, "state", "metrics");
|
|
36
|
-
const retentionDays = opts.retentionDays ?? 7;
|
|
37
|
-
const writeSnapshot = (snapshots: MetricSnapshot[]): void => {
|
|
38
|
-
try {
|
|
39
|
-
const date = new Date().toISOString().slice(0, 10);
|
|
40
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
41
|
-
rotateOldFiles(dir, retentionDays);
|
|
42
|
-
const redacted = redactSecrets(snapshots) as MetricSnapshot[];
|
|
43
|
-
fs.appendFileSync(path.join(dir, `${date}.jsonl`), `${JSON.stringify({ exportedAt: new Date().toISOString(), snapshots: redacted })}\n`, "utf-8");
|
|
44
|
-
} catch (error) {
|
|
45
|
-
logInternalError("metric-sink.write", error);
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
|
-
const timer = setInterval(() => writeSnapshot(opts.registry.snapshot()), opts.intervalMs ?? 60_000);
|
|
49
|
-
timer.unref?.();
|
|
50
|
-
return { writeSnapshot, dispose: () => clearInterval(timer) };
|
|
51
|
-
}
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { redactSecrets } from "../runtime/diagnostic-export.ts";
|
|
4
|
+
import { logInternalError } from "../utils/internal-error.ts";
|
|
5
|
+
import type { MetricRegistry } from "./metric-registry.ts";
|
|
6
|
+
import type { MetricSnapshot } from "./metrics-primitives.ts";
|
|
7
|
+
|
|
8
|
+
export interface MetricSink {
|
|
9
|
+
writeSnapshot(snapshots: MetricSnapshot[]): void;
|
|
10
|
+
dispose(): void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface MetricFileSinkOptions {
|
|
14
|
+
crewRoot: string;
|
|
15
|
+
registry: MetricRegistry;
|
|
16
|
+
retentionDays?: number;
|
|
17
|
+
intervalMs?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function rotateOldFiles(dir: string, retentionDays: number, now = Date.now()): void {
|
|
21
|
+
if (!fs.existsSync(dir)) return;
|
|
22
|
+
const maxAge = retentionDays * 24 * 60 * 60 * 1000;
|
|
23
|
+
for (const file of fs.readdirSync(dir)) {
|
|
24
|
+
if (!file.endsWith(".jsonl")) continue;
|
|
25
|
+
const fullPath = path.join(dir, file);
|
|
26
|
+
try {
|
|
27
|
+
if (now - fs.statSync(fullPath).mtimeMs > maxAge) fs.unlinkSync(fullPath);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
logInternalError("metric-sink.rotate", error, fullPath);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createMetricFileSink(opts: MetricFileSinkOptions): MetricSink {
|
|
35
|
+
const dir = path.join(opts.crewRoot, "state", "metrics");
|
|
36
|
+
const retentionDays = opts.retentionDays ?? 7;
|
|
37
|
+
const writeSnapshot = (snapshots: MetricSnapshot[]): void => {
|
|
38
|
+
try {
|
|
39
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
40
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
41
|
+
rotateOldFiles(dir, retentionDays);
|
|
42
|
+
const redacted = redactSecrets(snapshots) as MetricSnapshot[];
|
|
43
|
+
fs.appendFileSync(path.join(dir, `${date}.jsonl`), `${JSON.stringify({ exportedAt: new Date().toISOString(), snapshots: redacted })}\n`, "utf-8");
|
|
44
|
+
} catch (error) {
|
|
45
|
+
logInternalError("metric-sink.write", error);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
const timer = setInterval(() => writeSnapshot(opts.registry.snapshot()), opts.intervalMs ?? 60_000);
|
|
49
|
+
timer.unref?.();
|
|
50
|
+
return { writeSnapshot, dispose: () => clearInterval(timer) };
|
|
51
|
+
}
|