pi-crew 0.9.68 → 0.10.2
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/CHANGELOG.md +222 -0
- package/NOTICE.md +21 -0
- package/README.md +44 -2
- package/agents/analyst.md +1 -1
- package/agents/cold-verifier.md +3 -1
- package/agents/critic.md +1 -1
- package/agents/executor.md +1 -1
- package/agents/explorer.md +1 -1
- package/agents/planner.md +1 -1
- package/agents/reviewer.md +1 -1
- package/agents/security-reviewer.md +1 -1
- package/agents/test-engineer.md +1 -1
- package/agents/verifier.md +1 -1
- package/agents/writer.md +1 -1
- package/dist/index.mjs +68113 -60774
- package/docs/README.md +2 -0
- package/docs/actions-reference.md +31 -0
- package/docs/commands-reference.md +17 -6
- package/docs/resource-formats.md +13 -0
- package/package.json +4 -2
- package/schema.json +503 -91
- package/scripts/resource-sampler.mjs +36 -2
- package/skills/requirements-to-task-packet/SKILL.md +26 -0
- package/skills/widget-rendering/SKILL.md +7 -7
- package/src/agents/agent-config.ts +2 -1
- package/src/agents/discover-agents.ts +23 -14
- package/src/config/config-merge.ts +183 -0
- package/src/config/config-validation.ts +687 -0
- package/src/config/config.ts +22 -864
- package/src/config/defaults.ts +43 -2
- package/src/config/drift-detector.ts +1 -1
- package/src/config/env-vars.ts +691 -0
- package/src/config/role-tools.ts +11 -9
- package/src/config/sanitize-project-config.ts +172 -0
- package/src/config/types.ts +49 -1
- package/src/extension/async-notifier.ts +25 -2
- package/src/extension/crew-cleanup.ts +13 -0
- package/src/extension/crew-vibes/config.ts +2 -1
- package/src/extension/crew-vibes/footer.ts +19 -0
- package/src/extension/crew-vibes/index.ts +11 -1
- package/src/extension/plan-orchestrate.ts +132 -0
- package/src/extension/register.ts +8 -0
- package/src/extension/registration/command-registration.ts +1 -0
- package/src/extension/registration/commands/dashboard.ts +158 -0
- package/src/extension/registration/commands/index.ts +35 -0
- package/src/extension/registration/commands/manage.ts +303 -0
- package/src/extension/registration/commands/run.ts +228 -0
- package/src/extension/registration/commands/shared.ts +639 -0
- package/src/extension/registration/commands/status.ts +60 -0
- package/src/extension/registration/commands.ts +13 -1224
- package/src/extension/registration/foreground-run-controller.ts +10 -2
- package/src/extension/registration/lifecycle-handlers.ts +178 -17
- package/src/extension/registration/runtime-cleanup.ts +23 -5
- package/src/extension/registration/subagent-tools.ts +218 -9
- package/src/extension/registration/team-tool.ts +5 -1
- package/src/extension/registration/ui.ts +5 -4
- package/src/extension/rpc-hmac.ts +5 -3
- package/src/extension/team-tool/api/heartbeat.ts +47 -10
- package/src/extension/team-tool/api/plan-approval.ts +9 -0
- package/src/extension/team-tool/api/task-claims.ts +109 -40
- package/src/extension/team-tool/cancel.ts +84 -50
- package/src/extension/team-tool/dispatch/index.ts +1 -0
- package/src/extension/team-tool/dispatch/run.ts +4 -1
- package/src/extension/team-tool/doctor.ts +103 -1
- package/src/extension/team-tool/orchestrate.ts +66 -1
- package/src/extension/team-tool/plans.ts +192 -0
- package/src/extension/team-tool/respond.ts +197 -65
- package/src/extension/team-tool/run-deadline.ts +35 -3
- package/src/extension/team-tool/run-intent.ts +63 -0
- package/src/extension/team-tool/run.ts +74 -20
- package/src/extension/team-tool/status.ts +84 -26
- package/src/extension/team-tool.ts +11 -2
- package/src/hooks/registry.ts +1 -6
- package/src/i18n.ts +9 -0
- package/src/prompt/prompt-runtime.ts +521 -2
- package/src/prompt/worker-events-channel.ts +173 -0
- package/src/runtime/README.md +8 -8
- package/src/runtime/async-runner.ts +7 -3
- package/src/runtime/background-runner.ts +42 -14
- package/src/runtime/broker/broker-issuer.ts +9 -2
- package/src/runtime/broker/crew-broker-tokens.ts +43 -6
- package/src/runtime/broker/crew-broker.ts +838 -10
- package/src/runtime/broker/wait-status-cache.ts +157 -0
- package/src/runtime/budget-enforcement.ts +281 -0
- package/src/runtime/child-pi/child-pi-constants.ts +8 -0
- package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
- package/src/runtime/child-pi/child-pi-streams.ts +21 -1
- package/src/runtime/child-pi/child-pi-timers.ts +324 -0
- package/src/runtime/child-pi/child-pi.ts +97 -201
- package/src/runtime/child-pi/mock-fixtures.ts +16 -2
- package/src/runtime/crew-agent-records.ts +259 -14
- package/src/runtime/delegate-spawn.ts +148 -0
- package/src/runtime/detached-run-results.ts +90 -0
- package/src/runtime/deterministic-ast.ts +2 -1
- package/src/runtime/dispatch-batch.ts +945 -0
- package/src/runtime/finalize-run.ts +557 -0
- package/src/runtime/goal-workflow/adaptive-plan.ts +116 -15
- package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +8 -3
- package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
- package/src/runtime/group-join.ts +11 -125
- package/src/runtime/live-session/live-session-runtime.ts +26 -1
- package/src/runtime/merge-gate.ts +32 -10
- package/src/runtime/merge-loop.ts +130 -0
- package/src/runtime/model/model-budget-summary.ts +53 -0
- package/src/runtime/model/model-fallback.ts +36 -2
- package/src/runtime/model/pi-args.ts +10 -0
- package/src/runtime/model/provider-extensions.ts +10 -0
- package/src/runtime/orphan-worker-registry.ts +1 -1
- package/src/runtime/output/output-validator.ts +45 -0
- package/src/runtime/parent-guard.ts +3 -1
- package/src/runtime/peer-dep.ts +2 -1
- package/src/runtime/per-write-validator.ts +0 -5
- package/src/runtime/pi-spawn.ts +61 -15
- package/src/runtime/plan-approval.ts +125 -0
- package/src/runtime/plan-replan.ts +151 -0
- package/src/runtime/process-status.ts +16 -1
- package/src/runtime/recovery/checkpoint.ts +0 -18
- package/src/runtime/recovery/crash-recovery.ts +111 -46
- package/src/runtime/run-tracker.ts +77 -10
- package/src/runtime/scheduler-context.ts +98 -0
- package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
- package/src/runtime/scheduling/global-worker-cap.ts +2 -1
- package/src/runtime/scheduling/nested-slots.ts +70 -0
- package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
- package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
- package/src/runtime/settings-store.ts +219 -0
- package/src/runtime/spawn-policy.ts +217 -0
- package/src/runtime/stale-reconciler.ts +87 -6
- package/src/runtime/subagent-manager.ts +25 -1
- package/src/runtime/task-output-context.ts +230 -9
- package/src/runtime/task-packet.ts +23 -1
- package/src/runtime/task-runner/child-executor.ts +106 -7
- package/src/runtime/task-runner/post-execution.ts +125 -1
- package/src/runtime/task-runner/pre-execution.ts +39 -1
- package/src/runtime/task-runner/prompt-builder.ts +51 -1
- package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
- package/src/runtime/task-runner/spec-evidence.ts +403 -0
- package/src/runtime/task-runner/state-helpers.ts +26 -24
- package/src/runtime/task-runner.ts +11 -0
- package/src/runtime/team-runner.ts +132 -1673
- package/src/runtime/verification/spec-sandbox.ts +255 -0
- package/src/runtime/verification/verification-gates.ts +3 -2
- package/src/runtime/verification/verification-worktree.ts +2 -1
- package/src/runtime/workflow-phase-advance.ts +100 -0
- package/src/runtime/workspace-tree.ts +9 -0
- package/src/schema/config-schema.ts +66 -26
- package/src/schema/sensitive-config-paths.ts +64 -0
- package/src/schema/team-tool-schema.ts +13 -3
- package/src/state/README.md +4 -10
- package/src/state/atomic-write.ts +20 -3
- package/src/state/contracts.ts +38 -0
- package/src/state/coordination/mailbox.ts +12 -2
- package/src/state/event-log/cursor.ts +223 -0
- package/src/state/event-log/event-log-rotation.ts +12 -4
- package/src/state/event-log/event-log.ts +152 -369
- package/src/state/event-log/sequence-cache.ts +373 -0
- package/src/state/event-log/worker-atomic-writer.ts +2 -1
- package/src/state/stores/active-run-registry.ts +3 -2
- package/src/state/stores/manifest-io.ts +237 -0
- package/src/state/stores/ownership-map.ts +162 -0
- package/src/state/stores/plan-store.ts +241 -0
- package/src/state/stores/run-cache.ts +0 -90
- package/src/state/stores/spec-store.ts +189 -0
- package/src/state/stores/state-store.ts +139 -232
- package/src/state/types.ts +199 -0
- package/src/ui/dashboard-panes/plan-pane.ts +136 -0
- package/src/ui/dashboard-panes/progress-pane.ts +6 -0
- package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
- package/src/ui/dock-footer.ts +49 -0
- package/src/ui/heartbeat-aggregator.ts +9 -1
- package/src/ui/inline-panel/agent-pane.ts +375 -0
- package/src/ui/inline-panel/agent-transcript.ts +338 -0
- package/src/ui/inline-panel/agent-view-overlay.ts +225 -0
- package/src/ui/inline-panel/crew-editor.ts +192 -0
- package/src/ui/inline-panel/index.ts +290 -0
- package/src/ui/inline-panel/panel-rows.ts +37 -0
- package/src/ui/inline-panel/panel-selection.ts +157 -0
- package/src/ui/inline-panel/panel-store.ts +111 -0
- package/src/ui/inline-panel/view-session-store.ts +36 -0
- package/src/ui/keybinding-map.ts +54 -13
- package/src/ui/pi-ui-compat.ts +9 -0
- package/src/ui/powerbar-publisher.ts +52 -1
- package/src/ui/run-dashboard.ts +31 -5
- package/src/ui/run-snapshot-cache.ts +57 -30
- package/src/ui/snapshot-types.ts +6 -1
- package/src/ui/widget/index.ts +176 -22
- package/src/ui/widget/task-list.ts +198 -0
- package/src/ui/widget/widget-formatters.ts +240 -4
- package/src/ui/widget/widget-renderer.ts +243 -38
- package/src/ui/widget/widget-types.ts +11 -0
- package/src/utils/child-process-shield.ts +106 -0
- package/src/utils/file-coalescer.ts +0 -4
- package/src/utils/fs-errno.ts +66 -0
- package/src/utils/fs-watch.ts +1 -1
- package/src/utils/internal-error.ts +3 -1
- package/src/utils/paths.ts +11 -3
- package/src/utils/redaction.ts +7 -0
- package/src/utils/safe-abort.ts +45 -0
- package/src/utils/task-name-generator.ts +1 -8
- package/src/workflows/discover-workflows.ts +20 -2
- package/src/workflows/validate-workflow.ts +7 -1
- package/src/workflows/workflow-config.ts +17 -0
- package/src/workflows/workflow-serializer.ts +3 -0
- package/src/worktree/worktree-manager.ts +22 -0
- package/workflows/default.workflow.md +36 -26
- package/workflows/strict-fast-fix.workflow.md +26 -0
- package/src/agents/agent-search.ts +0 -98
- package/src/benchmark/benchmark-runner.ts +0 -313
- package/src/benchmark/feedback-loop.ts +0 -73
- package/src/config/resilient-parser.ts +0 -117
- package/src/extension/crew-vibes/cat-frames.ts +0 -18
- package/src/extension/result-watcher.ts +0 -139
- package/src/observability/exporters/prometheus-exporter.ts +0 -54
- package/src/observability/metric-retention.ts +0 -64
- package/src/runtime/compaction/compaction-summary.ts +0 -278
- package/src/runtime/errors/crew-errors.ts +0 -162
- package/src/runtime/live-session/intercom-bridge.ts +0 -187
- package/src/runtime/loop-gates.ts +0 -128
- package/src/runtime/metric-parser.ts +0 -36
- package/src/runtime/output/stream-preview.ts +0 -184
- package/src/runtime/output/tool-progress.ts +0 -278
- package/src/runtime/phase-tracker.ts +0 -385
- package/src/runtime/pipeline-runner.ts +0 -523
- package/src/runtime/process/process-lifecycle.ts +0 -491
- package/src/runtime/recovery/retry-runner.ts +0 -330
- package/src/runtime/run-drift.ts +0 -219
- package/src/runtime/task-quality.ts +0 -199
- package/src/runtime/task-runner/run-projection.ts +0 -128
- package/src/runtime/verification/post-checks.ts +0 -142
- package/src/state/coordination/schedule.ts +0 -166
- package/src/state/event-log/jsonl-writer.ts +0 -115
- package/src/state/hook-instinct-bridge.ts +0 -94
- package/src/state/hook-integrations.ts +0 -51
- package/src/state/session-state-map.ts +0 -51
- package/src/state/stores/blob-store.ts +0 -308
- package/src/state/stores/instinct-store.ts +0 -275
- package/src/state/stores/observation-store.ts +0 -176
- package/src/state/tiered-eval.ts +0 -480
- package/src/state/types-eval.ts +0 -58
- package/src/tools/safe-bash-extension.ts +0 -54
- package/src/tools/safe-bash.ts +0 -505
- package/src/ui/agent-management-overlay.ts +0 -160
- package/src/ui/crew-footer.ts +0 -102
- package/src/ui/crew-select-list.ts +0 -114
- package/src/ui/dashboard-panes/capability-pane.ts +0 -77
- package/src/ui/transcript-entries.ts +0 -256
- package/src/utils/conflict-detect.ts +0 -721
- package/src/utils/fingerprint.ts +0 -180
- package/src/utils/gh-protocol.ts +0 -556
- package/src/utils/project-detector.ts +0 -160
- package/src/utils/sse-parser.ts +0 -131
- package/src/workflows/cost-estimator.ts +0 -34
- package/src/workflows/intermediate-store.ts +0 -166
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import type { HistogramPoint, MetricLabels, MetricPoint, MetricSnapshot } from "../metrics-primitives.ts";
|
|
2
|
-
|
|
3
|
-
function prometheusName(name: string): string {
|
|
4
|
-
return name.replace(/[^a-zA-Z0-9_:]/g, "_").replace(/^[0-9]/, "_$&");
|
|
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
|
-
function formatPrometheusValue(num: number): string {
|
|
26
|
-
if (Number.isNaN(num)) return "Nan";
|
|
27
|
-
if (num === Number.POSITIVE_INFINITY) return "+Inf";
|
|
28
|
-
if (num === Number.NEGATIVE_INFINITY) return "-Inf";
|
|
29
|
-
return String(num);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function formatPrometheus(snapshots: MetricSnapshot[]): string {
|
|
33
|
-
const lines: string[] = [];
|
|
34
|
-
for (const snapshot of snapshots) {
|
|
35
|
-
const name = prometheusName(snapshot.name);
|
|
36
|
-
lines.push(`# HELP ${name} ${snapshot.description}`);
|
|
37
|
-
lines.push(`# TYPE ${name} ${metricType(snapshot.type)}`);
|
|
38
|
-
for (const value of snapshot.values) {
|
|
39
|
-
if (isHistogramPoint(value)) {
|
|
40
|
-
let cumulative = 0;
|
|
41
|
-
for (let index = 0; index < value.buckets.length; index += 1) {
|
|
42
|
-
cumulative += value.counts[index] ?? 0;
|
|
43
|
-
const le = Number.isFinite(value.buckets[index]) ? String(value.buckets[index]) : "+Inf";
|
|
44
|
-
lines.push(`${name}_bucket${labelsText({ ...value.labels, le })} ${cumulative}`);
|
|
45
|
-
}
|
|
46
|
-
lines.push(`${name}_sum${labelsText(value.labels)} ${value.sum}`);
|
|
47
|
-
lines.push(`${name}_count${labelsText(value.labels)} ${value.count}`);
|
|
48
|
-
} else {
|
|
49
|
-
lines.push(`${name}${labelsText(value.labels)} ${formatPrometheusValue(value.value)}`);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return `${lines.join("\n")}\n`;
|
|
54
|
-
}
|
|
@@ -1,64 +0,0 @@
|
|
|
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
|
-
private static readonly MAX_EVENTS = 100_000;
|
|
14
|
-
|
|
15
|
-
constructor(windowMs = 3_600_000, now: () => number = () => Date.now()) {
|
|
16
|
-
this.windowMs = windowMs;
|
|
17
|
-
this.now = now;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
inc(labels: MetricLabels = {}, delta = 1): void {
|
|
21
|
-
if (!Number.isFinite(delta)) return;
|
|
22
|
-
// Cap the event array to prevent unbounded memory growth.
|
|
23
|
-
if (this.events.length >= TimeWindowedCounter.MAX_EVENTS) this.prune();
|
|
24
|
-
this.events.push({
|
|
25
|
-
timestamp: this.now(),
|
|
26
|
-
labels: { ...labels },
|
|
27
|
-
delta,
|
|
28
|
-
});
|
|
29
|
-
this.prune();
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// PERF (OBS-5): This method is O(N) per call because it linearly scans
|
|
33
|
-
// all events and calls labelKey() (which uses JSON.stringify) on each.
|
|
34
|
-
// A more efficient aggregation (e.g., pre-aggregated label buckets or a
|
|
35
|
-
// sliding-window histogram) is planned to replace this hot path.
|
|
36
|
-
count(labels: MetricLabels = {}, durationMs = this.windowMs): number {
|
|
37
|
-
const now = this.now();
|
|
38
|
-
this.pruneAt(now);
|
|
39
|
-
const key = labelKey(labels);
|
|
40
|
-
const cutoff = now - durationMs;
|
|
41
|
-
return this.events
|
|
42
|
-
.filter((event) => event.timestamp >= cutoff && labelKey(event.labels) === key)
|
|
43
|
-
.reduce((sum, event) => sum + event.delta, 0);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
rate(labels: MetricLabels = {}, durationMs = this.windowMs): number {
|
|
47
|
-
if (durationMs <= 0) return 0;
|
|
48
|
-
return this.count(labels, durationMs) / (durationMs / 1000);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
size(): number {
|
|
52
|
-
this.prune();
|
|
53
|
-
return this.events.length;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
private prune(): void {
|
|
57
|
-
this.pruneAt(this.now());
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
private pruneAt(now: number): void {
|
|
61
|
-
const cutoff = now - this.windowMs;
|
|
62
|
-
this.events = this.events.filter((event) => event.timestamp >= cutoff);
|
|
63
|
-
}
|
|
64
|
-
}
|
|
@@ -1,278 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Deterministic compaction summary — builds a markdown summary of a pi-crew run
|
|
3
|
-
* from manifest.json, tasks.json, and the tail of events.jsonl.
|
|
4
|
-
*
|
|
5
|
-
* Distilled from pi-autoresearch's compaction-summary pattern.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
class GiantLineFallbackError extends Error {
|
|
9
|
-
constructor() {
|
|
10
|
-
super("GIANT_LINE_FALLBACK");
|
|
11
|
-
this.name = "GiantLineFallbackError";
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
import * as fs from "node:fs";
|
|
16
|
-
import * as path from "node:path";
|
|
17
|
-
import { readJsonFile } from "../../state/atomic-write.ts";
|
|
18
|
-
import type { TeamEvent } from "../../state/event-log/event-log.ts";
|
|
19
|
-
import type { TeamRunManifest, TeamTaskState } from "../../state/types.ts";
|
|
20
|
-
|
|
21
|
-
/** Maximum number of events to read from the tail of events.jsonl. */
|
|
22
|
-
const MAX_TAIL_EVENTS = 100;
|
|
23
|
-
|
|
24
|
-
/** Maximum number of completed tasks to include in the "Recent Results" section. */
|
|
25
|
-
const MAX_RECENT_RESULTS = 10;
|
|
26
|
-
|
|
27
|
-
/** Paths relevant to building a compaction summary for a run. */
|
|
28
|
-
export interface SummaryPaths {
|
|
29
|
-
manifestPath: string;
|
|
30
|
-
tasksPath: string;
|
|
31
|
-
eventsPath: string;
|
|
32
|
-
stateRoot: string;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Derive the standard summary-relevant paths from a state root directory.
|
|
37
|
-
* Mirrors pi-autoresearch's `autoresearchSummaryPathsFor()`.
|
|
38
|
-
*/
|
|
39
|
-
export function summaryPathsFor(stateRoot: string): SummaryPaths {
|
|
40
|
-
return {
|
|
41
|
-
stateRoot,
|
|
42
|
-
manifestPath: path.join(stateRoot, "manifest.json"),
|
|
43
|
-
tasksPath: path.join(stateRoot, "tasks.json"),
|
|
44
|
-
eventsPath: path.join(stateRoot, "events.jsonl"),
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Read the last N lines from a text file.
|
|
50
|
-
* Uses reverse buffer reading to avoid loading the entire file into memory.
|
|
51
|
-
* For files larger than TAIL_MAX_READ bytes, only the last chunk is read.
|
|
52
|
-
*/
|
|
53
|
-
const TAIL_MAX_READ = 256 * 1024; // 256KB — enough for ~1000 lines of JSONL
|
|
54
|
-
const MAX_FALLBACK_READ = 2 * 1024 * 1024; // 2MB — safety limit for giant-line fallback
|
|
55
|
-
function readTailLines(filePath: string, maxLines: number): string[] {
|
|
56
|
-
if (!fs.existsSync(filePath)) return [];
|
|
57
|
-
try {
|
|
58
|
-
const stat = fs.statSync(filePath);
|
|
59
|
-
const fileSize = stat.size;
|
|
60
|
-
if (fileSize === 0) return [];
|
|
61
|
-
|
|
62
|
-
// For small files, just read everything
|
|
63
|
-
if (fileSize <= TAIL_MAX_READ) {
|
|
64
|
-
const content = fs.readFileSync(filePath, "utf-8");
|
|
65
|
-
return content
|
|
66
|
-
.split("\n")
|
|
67
|
-
.filter((line) => line.trim().length > 0)
|
|
68
|
-
.slice(-maxLines);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// For large files, read only the last chunk.
|
|
72
|
-
// Search backwards from the read boundary for a newline to avoid
|
|
73
|
-
// splitting mid-line or mid-multibyte UTF-8 character.
|
|
74
|
-
const fd = fs.openSync(filePath, "r");
|
|
75
|
-
try {
|
|
76
|
-
const readSize = Math.min(fileSize, TAIL_MAX_READ);
|
|
77
|
-
const readOffset = fileSize - readSize;
|
|
78
|
-
const buf = Buffer.alloc(readSize);
|
|
79
|
-
fs.readSync(fd, buf, 0, readSize, readOffset);
|
|
80
|
-
|
|
81
|
-
// Find the first newline in the buffer to avoid partial lines.
|
|
82
|
-
// This also handles multibyte UTF-8 safety — we start after a
|
|
83
|
-
// newline boundary which is always a clean character boundary.
|
|
84
|
-
let start = 0;
|
|
85
|
-
if (readOffset > 0) {
|
|
86
|
-
const firstNewline = buf.indexOf("\n");
|
|
87
|
-
if (firstNewline >= 0) {
|
|
88
|
-
start = firstNewline + 1;
|
|
89
|
-
} else {
|
|
90
|
-
// No newline found in the entire tail chunk — single giant line.
|
|
91
|
-
// Fall back to reading the full file to avoid data loss.
|
|
92
|
-
// Note: fd will be closed by the outer finally block.
|
|
93
|
-
throw new GiantLineFallbackError();
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const content = buf.toString("utf-8", start, readSize);
|
|
98
|
-
const lines = content.split("\n").filter((line) => line.trim().length > 0);
|
|
99
|
-
return lines.slice(-maxLines);
|
|
100
|
-
} finally {
|
|
101
|
-
fs.closeSync(fd);
|
|
102
|
-
}
|
|
103
|
-
} catch (err) {
|
|
104
|
-
// Giant-line fallback: fd already closed by finally above.
|
|
105
|
-
if (err instanceof GiantLineFallbackError) {
|
|
106
|
-
const stat = fs.statSync(filePath);
|
|
107
|
-
if (stat.size > MAX_FALLBACK_READ) return [];
|
|
108
|
-
const content = fs.readFileSync(filePath, "utf-8");
|
|
109
|
-
return content
|
|
110
|
-
.split("\n")
|
|
111
|
-
.filter((line) => line.trim().length > 0)
|
|
112
|
-
.slice(-maxLines);
|
|
113
|
-
}
|
|
114
|
-
return [];
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Parse JSONL lines into TeamEvent objects, skipping malformed lines.
|
|
120
|
-
*/
|
|
121
|
-
function parseEvents(lines: string[]): TeamEvent[] {
|
|
122
|
-
const events: TeamEvent[] = [];
|
|
123
|
-
for (const line of lines) {
|
|
124
|
-
try {
|
|
125
|
-
const parsed = JSON.parse(line.trim());
|
|
126
|
-
if (typeof parsed === "object" && parsed !== null && typeof parsed.type === "string" && typeof parsed.runId === "string") {
|
|
127
|
-
events.push(parsed as TeamEvent);
|
|
128
|
-
}
|
|
129
|
-
} catch {
|
|
130
|
-
// Skip malformed lines
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
return events;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Compute a human-readable duration between two ISO timestamp strings.
|
|
138
|
-
*/
|
|
139
|
-
function formatDuration(startIso?: string, endIso?: string): string {
|
|
140
|
-
if (!startIso) return "—";
|
|
141
|
-
const start = new Date(startIso).getTime();
|
|
142
|
-
if (Number.isNaN(start)) return "—";
|
|
143
|
-
const end = endIso ? new Date(endIso).getTime() : Date.now();
|
|
144
|
-
if (Number.isNaN(end)) return "—";
|
|
145
|
-
const diffMs = end - start;
|
|
146
|
-
if (diffMs < 0) return "—";
|
|
147
|
-
const seconds = Math.floor(diffMs / 1000);
|
|
148
|
-
if (seconds < 60) return `${seconds}s`;
|
|
149
|
-
const minutes = Math.floor(seconds / 60);
|
|
150
|
-
const remainingSeconds = seconds % 60;
|
|
151
|
-
if (minutes < 60) return `${minutes}m ${remainingSeconds}s`;
|
|
152
|
-
const hours = Math.floor(minutes / 60);
|
|
153
|
-
const remainingMinutes = minutes % 60;
|
|
154
|
-
return `${hours}h ${remainingMinutes}m`;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* Build a deterministic compaction summary for a pi-crew run.
|
|
159
|
-
*
|
|
160
|
-
* Reads manifest.json, tasks.json, and the tail of events.jsonl to produce
|
|
161
|
-
* a self-contained markdown summary suitable for context injection.
|
|
162
|
-
*
|
|
163
|
-
* @param stateRoot - Path to the run's state root directory
|
|
164
|
-
* @returns Markdown-formatted compaction summary
|
|
165
|
-
*/
|
|
166
|
-
export function buildCompactionSummary(stateRoot: string): string {
|
|
167
|
-
const paths = summaryPathsFor(stateRoot);
|
|
168
|
-
|
|
169
|
-
// Read manifest
|
|
170
|
-
const manifest = readJsonFile<TeamRunManifest>(paths.manifestPath);
|
|
171
|
-
|
|
172
|
-
// Read tasks
|
|
173
|
-
const tasks = readJsonFile<TeamTaskState[]>(paths.tasksPath) ?? [];
|
|
174
|
-
|
|
175
|
-
// Read tail events
|
|
176
|
-
const tailLines = readTailLines(paths.eventsPath, MAX_TAIL_EVENTS);
|
|
177
|
-
const tailEvents = parseEvents(tailLines);
|
|
178
|
-
|
|
179
|
-
const sections: string[] = [];
|
|
180
|
-
|
|
181
|
-
// Section: Run Metadata
|
|
182
|
-
sections.push("# Run Summary");
|
|
183
|
-
if (manifest) {
|
|
184
|
-
sections.push("");
|
|
185
|
-
sections.push("## Run Metadata");
|
|
186
|
-
sections.push(`- **Run ID**: ${manifest.runId}`);
|
|
187
|
-
sections.push(`- **Team**: ${manifest.team}`);
|
|
188
|
-
if (manifest.workflow) {
|
|
189
|
-
sections.push(`- **Workflow**: ${manifest.workflow}`);
|
|
190
|
-
}
|
|
191
|
-
if (manifest.goal) {
|
|
192
|
-
sections.push(`- **Goal**: ${manifest.goal.replace(/\n/g, " ").slice(0, 500)}`);
|
|
193
|
-
}
|
|
194
|
-
sections.push(`- **Status**: ${manifest.status}`);
|
|
195
|
-
sections.push(`- **Created**: ${manifest.createdAt}`);
|
|
196
|
-
sections.push(`- **Updated**: ${manifest.updatedAt}`);
|
|
197
|
-
if (manifest.workspaceMode) {
|
|
198
|
-
sections.push(`- **Workspace Mode**: ${manifest.workspaceMode}`);
|
|
199
|
-
}
|
|
200
|
-
} else {
|
|
201
|
-
sections.push("");
|
|
202
|
-
sections.push("## Run Metadata");
|
|
203
|
-
sections.push("- **Status**: manifest unavailable");
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// Section: Task Progress Table
|
|
207
|
-
sections.push("");
|
|
208
|
-
sections.push("## Task Progress");
|
|
209
|
-
if (tasks.length > 0) {
|
|
210
|
-
sections.push("");
|
|
211
|
-
sections.push("| ID | Role | Status | Duration |");
|
|
212
|
-
sections.push("|---|---|---|---|");
|
|
213
|
-
for (const task of tasks) {
|
|
214
|
-
const taskId = task.id;
|
|
215
|
-
const role = task.role || "—";
|
|
216
|
-
const status = task.status || "—";
|
|
217
|
-
const duration = formatDuration(task.startedAt, task.finishedAt);
|
|
218
|
-
sections.push(`| ${taskId} | ${role} | ${status} | ${duration} |`);
|
|
219
|
-
}
|
|
220
|
-
} else {
|
|
221
|
-
sections.push("");
|
|
222
|
-
sections.push("No tasks recorded.");
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// Section: Recent Task Results
|
|
226
|
-
const completedTasks = tasks.filter((t) => t.status === "completed" || t.status === "failed").slice(-MAX_RECENT_RESULTS);
|
|
227
|
-
|
|
228
|
-
if (completedTasks.length > 0) {
|
|
229
|
-
sections.push("");
|
|
230
|
-
sections.push("## Recent Task Results");
|
|
231
|
-
for (const task of completedTasks) {
|
|
232
|
-
sections.push("");
|
|
233
|
-
sections.push(`### ${task.id} (${task.status})`);
|
|
234
|
-
if (task.error) {
|
|
235
|
-
sections.push(`- **Error**: ${task.error}`);
|
|
236
|
-
}
|
|
237
|
-
if (task.diagnostics && Object.keys(task.diagnostics).length > 0) {
|
|
238
|
-
sections.push("- **Diagnostics**:");
|
|
239
|
-
for (const [key, value] of Object.entries(task.diagnostics)) {
|
|
240
|
-
sections.push(` - ${key}: ${JSON.stringify(value)}`);
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
if (task.metrics && Object.keys(task.metrics).length > 0) {
|
|
244
|
-
sections.push("- **Metrics**:");
|
|
245
|
-
for (const [key, value] of Object.entries(task.metrics)) {
|
|
246
|
-
sections.push(` - ${key}: ${value}`);
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
// Section: Next Steps (pending/queued tasks)
|
|
253
|
-
const pendingStatuses = new Set(["queued", "waiting", "running"]);
|
|
254
|
-
const pendingTasks = tasks.filter((t) => pendingStatuses.has(t.status));
|
|
255
|
-
if (pendingTasks.length > 0) {
|
|
256
|
-
sections.push("");
|
|
257
|
-
sections.push("## Next Steps");
|
|
258
|
-
sections.push("");
|
|
259
|
-
for (const task of pendingTasks) {
|
|
260
|
-
const title = task.title || task.role || "Untitled";
|
|
261
|
-
sections.push(`- [${task.status}] ${task.id}: ${title}`);
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// Section: Tail Events Summary
|
|
266
|
-
if (tailEvents.length > 0) {
|
|
267
|
-
sections.push("");
|
|
268
|
-
sections.push(`## Recent Events (last ${tailEvents.length})`);
|
|
269
|
-
sections.push("");
|
|
270
|
-
for (const event of tailEvents.slice(-10)) {
|
|
271
|
-
const taskPart = event.taskId ? ` task=${event.taskId}` : "";
|
|
272
|
-
const msgPart = event.message ? ` — ${event.message}` : "";
|
|
273
|
-
sections.push(`- [${event.time}] ${event.type}${taskPart}${msgPart}`);
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
return sections.join("\n");
|
|
278
|
-
}
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* crew-errors.ts — Typed error sentinels for pi-crew operations.
|
|
3
|
-
*
|
|
4
|
-
* Based on oh-my-pi pattern from compaction/errors.ts.
|
|
5
|
-
* Uses `instanceof` discrimination instead of string matching.
|
|
6
|
-
*
|
|
7
|
-
* NOTE: Constructor parameters are explicit properties (not TypeScript
|
|
8
|
-
* parameter properties) for strip-types compatibility.
|
|
9
|
-
*
|
|
10
|
-
* The `name` property is not set on instances because JavaScript's `name`
|
|
11
|
-
* on functions is special and can't be overridden. Use `instanceof` checks
|
|
12
|
-
* or the `code` property for discrimination.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
/** Base class for all pi-crew errors. */
|
|
16
|
-
export abstract class CrewError extends Error {
|
|
17
|
-
abstract readonly code: string;
|
|
18
|
-
|
|
19
|
-
/** Returns the class name. Use `instanceof` for discrimination. */
|
|
20
|
-
toString(): string {
|
|
21
|
-
return `[${this.constructor.name}] ${this.message}`;
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/** Raised when a crew run is explicitly cancelled by user or API. */
|
|
26
|
-
export class CrewCancelledError extends CrewError {
|
|
27
|
-
readonly code = "CREW_CANCELLED";
|
|
28
|
-
constructor(message = "Crew run cancelled") {
|
|
29
|
-
super(message);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** Raised when a crew run exceeds its configured maximum duration. */
|
|
34
|
-
export class CrewTimeoutError extends CrewError {
|
|
35
|
-
readonly code = "CREW_TIMEOUT";
|
|
36
|
-
readonly maxDurationMs: number;
|
|
37
|
-
constructor(maxDurationMs: number, message?: string) {
|
|
38
|
-
super(message ?? `Crew run exceeded timeout of ${maxDurationMs}ms`);
|
|
39
|
-
this.maxDurationMs = maxDurationMs;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Raised when an individual agent in a crew goes deadletter — i.e. it
|
|
45
|
-
* encountered an unrecoverable error that blocks its task from completing.
|
|
46
|
-
* Common causes: crash, OOM, unhandled exception in tool execution.
|
|
47
|
-
*/
|
|
48
|
-
export class CrewDeadletterError extends CrewError {
|
|
49
|
-
readonly code = "CREW_DEADLETTER";
|
|
50
|
-
readonly agentId: string;
|
|
51
|
-
readonly reason: string;
|
|
52
|
-
constructor(agentId: string, reason: string, message?: string) {
|
|
53
|
-
super(message ?? `Agent ${agentId} deadlettered: ${reason}`);
|
|
54
|
-
this.agentId = agentId;
|
|
55
|
-
this.reason = reason;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** Raised when a crew run is aborted — operator Esc, SIGINT, or similar. */
|
|
60
|
-
export class CrewAbortError extends CrewError {
|
|
61
|
-
readonly code = "CREW_ABORT";
|
|
62
|
-
constructor(message = "Crew run aborted") {
|
|
63
|
-
super(message);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** Raised when a manifest or task file is malformed or missing required fields. */
|
|
68
|
-
export class CrewManifestError extends CrewError {
|
|
69
|
-
readonly code = "CREW_MANIFEST_ERROR";
|
|
70
|
-
readonly runId?: string;
|
|
71
|
-
readonly taskId?: string;
|
|
72
|
-
constructor(message: string, runId?: string, taskId?: string) {
|
|
73
|
-
super(message);
|
|
74
|
-
this.runId = runId;
|
|
75
|
-
this.taskId = taskId;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Raised when a lock cannot be acquired or is held by a stale process. */
|
|
80
|
-
export class CrewLockError extends CrewError {
|
|
81
|
-
readonly code = "CREW_LOCK_ERROR";
|
|
82
|
-
readonly lockPath?: string;
|
|
83
|
-
constructor(message: string, lockPath?: string) {
|
|
84
|
-
super(message);
|
|
85
|
-
this.lockPath = lockPath;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** Raised when an agent exceeds its turn limit. */
|
|
90
|
-
export class CrewTurnLimitError extends CrewError {
|
|
91
|
-
readonly code = "CREW_TURN_LIMIT";
|
|
92
|
-
readonly agentId: string;
|
|
93
|
-
readonly maxTurns: number;
|
|
94
|
-
constructor(agentId: string, maxTurns: number) {
|
|
95
|
-
super(`Agent ${agentId} exceeded turn limit of ${maxTurns}`);
|
|
96
|
-
this.agentId = agentId;
|
|
97
|
-
this.maxTurns = maxTurns;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Raised when a workflow step gate condition is not met. */
|
|
102
|
-
export class CrewGateError extends CrewError {
|
|
103
|
-
readonly code = "CREW_GATE_ERROR";
|
|
104
|
-
readonly gateName: string;
|
|
105
|
-
constructor(gateName: string, message: string) {
|
|
106
|
-
super(message);
|
|
107
|
-
this.gateName = gateName;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** Raised when an agent session fails to initialize (e.g. model not found). */
|
|
112
|
-
export class CrewSessionError extends CrewError {
|
|
113
|
-
readonly code = "CREW_SESSION_ERROR";
|
|
114
|
-
readonly agentId?: string;
|
|
115
|
-
constructor(message: string, agentId?: string) {
|
|
116
|
-
super(message);
|
|
117
|
-
this.agentId = agentId;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* Outcome of a crew run attempt.
|
|
123
|
-
* Used by RunTracker and health monitoring for outcome classification.
|
|
124
|
-
*/
|
|
125
|
-
export type CrewRunOutcome =
|
|
126
|
-
| "ok" // Completed successfully
|
|
127
|
-
| "cancelled" // Explicitly cancelled by user or API
|
|
128
|
-
| "deadletter" // Agent encountered unrecoverable error
|
|
129
|
-
| "failed" // Workflow step failed (gate error, etc.)
|
|
130
|
-
| "timeout" // Exceeded max duration
|
|
131
|
-
| "aborted"; // Operator interrupt (Esc, SIGINT)
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Classify a thrown error into a CrewRunOutcome.
|
|
135
|
-
* Useful in catch blocks that need to determine run outcome.
|
|
136
|
-
*/
|
|
137
|
-
export function classifyError(error: unknown): CrewRunOutcome {
|
|
138
|
-
if (error instanceof CrewCancelledError) return "cancelled";
|
|
139
|
-
if (error instanceof CrewTimeoutError) return "timeout";
|
|
140
|
-
if (error instanceof CrewDeadletterError) return "deadletter";
|
|
141
|
-
if (error instanceof CrewAbortError) return "aborted";
|
|
142
|
-
if (error instanceof CrewGateError) return "failed";
|
|
143
|
-
if (error instanceof CrewError) return "failed";
|
|
144
|
-
// Unknown errors → failed
|
|
145
|
-
return "failed";
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Check if an error indicates the run was intentionally interrupted
|
|
150
|
-
* (cancelled, aborted, or timed out) vs a genuine failure.
|
|
151
|
-
*/
|
|
152
|
-
export function isInterruptError(error: unknown): boolean {
|
|
153
|
-
return error instanceof CrewCancelledError || error instanceof CrewAbortError || error instanceof CrewTimeoutError;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Check if an error indicates the run failed due to agent malfunction
|
|
158
|
-
* rather than workflow logic or user action.
|
|
159
|
-
*/
|
|
160
|
-
export function isAgentError(error: unknown): boolean {
|
|
161
|
-
return error instanceof CrewDeadletterError || error instanceof CrewTurnLimitError || error instanceof CrewSessionError;
|
|
162
|
-
}
|