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.
Files changed (253) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/NOTICE.md +21 -0
  3. package/README.md +44 -2
  4. package/agents/analyst.md +1 -1
  5. package/agents/cold-verifier.md +3 -1
  6. package/agents/critic.md +1 -1
  7. package/agents/executor.md +1 -1
  8. package/agents/explorer.md +1 -1
  9. package/agents/planner.md +1 -1
  10. package/agents/reviewer.md +1 -1
  11. package/agents/security-reviewer.md +1 -1
  12. package/agents/test-engineer.md +1 -1
  13. package/agents/verifier.md +1 -1
  14. package/agents/writer.md +1 -1
  15. package/dist/index.mjs +68113 -60774
  16. package/docs/README.md +2 -0
  17. package/docs/actions-reference.md +31 -0
  18. package/docs/commands-reference.md +17 -6
  19. package/docs/resource-formats.md +13 -0
  20. package/package.json +4 -2
  21. package/schema.json +503 -91
  22. package/scripts/resource-sampler.mjs +36 -2
  23. package/skills/requirements-to-task-packet/SKILL.md +26 -0
  24. package/skills/widget-rendering/SKILL.md +7 -7
  25. package/src/agents/agent-config.ts +2 -1
  26. package/src/agents/discover-agents.ts +23 -14
  27. package/src/config/config-merge.ts +183 -0
  28. package/src/config/config-validation.ts +687 -0
  29. package/src/config/config.ts +22 -864
  30. package/src/config/defaults.ts +43 -2
  31. package/src/config/drift-detector.ts +1 -1
  32. package/src/config/env-vars.ts +691 -0
  33. package/src/config/role-tools.ts +11 -9
  34. package/src/config/sanitize-project-config.ts +172 -0
  35. package/src/config/types.ts +49 -1
  36. package/src/extension/async-notifier.ts +25 -2
  37. package/src/extension/crew-cleanup.ts +13 -0
  38. package/src/extension/crew-vibes/config.ts +2 -1
  39. package/src/extension/crew-vibes/footer.ts +19 -0
  40. package/src/extension/crew-vibes/index.ts +11 -1
  41. package/src/extension/plan-orchestrate.ts +132 -0
  42. package/src/extension/register.ts +8 -0
  43. package/src/extension/registration/command-registration.ts +1 -0
  44. package/src/extension/registration/commands/dashboard.ts +158 -0
  45. package/src/extension/registration/commands/index.ts +35 -0
  46. package/src/extension/registration/commands/manage.ts +303 -0
  47. package/src/extension/registration/commands/run.ts +228 -0
  48. package/src/extension/registration/commands/shared.ts +639 -0
  49. package/src/extension/registration/commands/status.ts +60 -0
  50. package/src/extension/registration/commands.ts +13 -1224
  51. package/src/extension/registration/foreground-run-controller.ts +10 -2
  52. package/src/extension/registration/lifecycle-handlers.ts +178 -17
  53. package/src/extension/registration/runtime-cleanup.ts +23 -5
  54. package/src/extension/registration/subagent-tools.ts +218 -9
  55. package/src/extension/registration/team-tool.ts +5 -1
  56. package/src/extension/registration/ui.ts +5 -4
  57. package/src/extension/rpc-hmac.ts +5 -3
  58. package/src/extension/team-tool/api/heartbeat.ts +47 -10
  59. package/src/extension/team-tool/api/plan-approval.ts +9 -0
  60. package/src/extension/team-tool/api/task-claims.ts +109 -40
  61. package/src/extension/team-tool/cancel.ts +84 -50
  62. package/src/extension/team-tool/dispatch/index.ts +1 -0
  63. package/src/extension/team-tool/dispatch/run.ts +4 -1
  64. package/src/extension/team-tool/doctor.ts +103 -1
  65. package/src/extension/team-tool/orchestrate.ts +66 -1
  66. package/src/extension/team-tool/plans.ts +192 -0
  67. package/src/extension/team-tool/respond.ts +197 -65
  68. package/src/extension/team-tool/run-deadline.ts +35 -3
  69. package/src/extension/team-tool/run-intent.ts +63 -0
  70. package/src/extension/team-tool/run.ts +74 -20
  71. package/src/extension/team-tool/status.ts +84 -26
  72. package/src/extension/team-tool.ts +11 -2
  73. package/src/hooks/registry.ts +1 -6
  74. package/src/i18n.ts +9 -0
  75. package/src/prompt/prompt-runtime.ts +521 -2
  76. package/src/prompt/worker-events-channel.ts +173 -0
  77. package/src/runtime/README.md +8 -8
  78. package/src/runtime/async-runner.ts +7 -3
  79. package/src/runtime/background-runner.ts +42 -14
  80. package/src/runtime/broker/broker-issuer.ts +9 -2
  81. package/src/runtime/broker/crew-broker-tokens.ts +43 -6
  82. package/src/runtime/broker/crew-broker.ts +838 -10
  83. package/src/runtime/broker/wait-status-cache.ts +157 -0
  84. package/src/runtime/budget-enforcement.ts +281 -0
  85. package/src/runtime/child-pi/child-pi-constants.ts +8 -0
  86. package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
  87. package/src/runtime/child-pi/child-pi-streams.ts +21 -1
  88. package/src/runtime/child-pi/child-pi-timers.ts +324 -0
  89. package/src/runtime/child-pi/child-pi.ts +97 -201
  90. package/src/runtime/child-pi/mock-fixtures.ts +16 -2
  91. package/src/runtime/crew-agent-records.ts +259 -14
  92. package/src/runtime/delegate-spawn.ts +148 -0
  93. package/src/runtime/detached-run-results.ts +90 -0
  94. package/src/runtime/deterministic-ast.ts +2 -1
  95. package/src/runtime/dispatch-batch.ts +945 -0
  96. package/src/runtime/finalize-run.ts +557 -0
  97. package/src/runtime/goal-workflow/adaptive-plan.ts +116 -15
  98. package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +8 -3
  99. package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
  100. package/src/runtime/group-join.ts +11 -125
  101. package/src/runtime/live-session/live-session-runtime.ts +26 -1
  102. package/src/runtime/merge-gate.ts +32 -10
  103. package/src/runtime/merge-loop.ts +130 -0
  104. package/src/runtime/model/model-budget-summary.ts +53 -0
  105. package/src/runtime/model/model-fallback.ts +36 -2
  106. package/src/runtime/model/pi-args.ts +10 -0
  107. package/src/runtime/model/provider-extensions.ts +10 -0
  108. package/src/runtime/orphan-worker-registry.ts +1 -1
  109. package/src/runtime/output/output-validator.ts +45 -0
  110. package/src/runtime/parent-guard.ts +3 -1
  111. package/src/runtime/peer-dep.ts +2 -1
  112. package/src/runtime/per-write-validator.ts +0 -5
  113. package/src/runtime/pi-spawn.ts +61 -15
  114. package/src/runtime/plan-approval.ts +125 -0
  115. package/src/runtime/plan-replan.ts +151 -0
  116. package/src/runtime/process-status.ts +16 -1
  117. package/src/runtime/recovery/checkpoint.ts +0 -18
  118. package/src/runtime/recovery/crash-recovery.ts +111 -46
  119. package/src/runtime/run-tracker.ts +77 -10
  120. package/src/runtime/scheduler-context.ts +98 -0
  121. package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
  122. package/src/runtime/scheduling/global-worker-cap.ts +2 -1
  123. package/src/runtime/scheduling/nested-slots.ts +70 -0
  124. package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
  125. package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
  126. package/src/runtime/settings-store.ts +219 -0
  127. package/src/runtime/spawn-policy.ts +217 -0
  128. package/src/runtime/stale-reconciler.ts +87 -6
  129. package/src/runtime/subagent-manager.ts +25 -1
  130. package/src/runtime/task-output-context.ts +230 -9
  131. package/src/runtime/task-packet.ts +23 -1
  132. package/src/runtime/task-runner/child-executor.ts +106 -7
  133. package/src/runtime/task-runner/post-execution.ts +125 -1
  134. package/src/runtime/task-runner/pre-execution.ts +39 -1
  135. package/src/runtime/task-runner/prompt-builder.ts +51 -1
  136. package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
  137. package/src/runtime/task-runner/spec-evidence.ts +403 -0
  138. package/src/runtime/task-runner/state-helpers.ts +26 -24
  139. package/src/runtime/task-runner.ts +11 -0
  140. package/src/runtime/team-runner.ts +132 -1673
  141. package/src/runtime/verification/spec-sandbox.ts +255 -0
  142. package/src/runtime/verification/verification-gates.ts +3 -2
  143. package/src/runtime/verification/verification-worktree.ts +2 -1
  144. package/src/runtime/workflow-phase-advance.ts +100 -0
  145. package/src/runtime/workspace-tree.ts +9 -0
  146. package/src/schema/config-schema.ts +66 -26
  147. package/src/schema/sensitive-config-paths.ts +64 -0
  148. package/src/schema/team-tool-schema.ts +13 -3
  149. package/src/state/README.md +4 -10
  150. package/src/state/atomic-write.ts +20 -3
  151. package/src/state/contracts.ts +38 -0
  152. package/src/state/coordination/mailbox.ts +12 -2
  153. package/src/state/event-log/cursor.ts +223 -0
  154. package/src/state/event-log/event-log-rotation.ts +12 -4
  155. package/src/state/event-log/event-log.ts +152 -369
  156. package/src/state/event-log/sequence-cache.ts +373 -0
  157. package/src/state/event-log/worker-atomic-writer.ts +2 -1
  158. package/src/state/stores/active-run-registry.ts +3 -2
  159. package/src/state/stores/manifest-io.ts +237 -0
  160. package/src/state/stores/ownership-map.ts +162 -0
  161. package/src/state/stores/plan-store.ts +241 -0
  162. package/src/state/stores/run-cache.ts +0 -90
  163. package/src/state/stores/spec-store.ts +189 -0
  164. package/src/state/stores/state-store.ts +139 -232
  165. package/src/state/types.ts +199 -0
  166. package/src/ui/dashboard-panes/plan-pane.ts +136 -0
  167. package/src/ui/dashboard-panes/progress-pane.ts +6 -0
  168. package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
  169. package/src/ui/dock-footer.ts +49 -0
  170. package/src/ui/heartbeat-aggregator.ts +9 -1
  171. package/src/ui/inline-panel/agent-pane.ts +375 -0
  172. package/src/ui/inline-panel/agent-transcript.ts +338 -0
  173. package/src/ui/inline-panel/agent-view-overlay.ts +225 -0
  174. package/src/ui/inline-panel/crew-editor.ts +192 -0
  175. package/src/ui/inline-panel/index.ts +290 -0
  176. package/src/ui/inline-panel/panel-rows.ts +37 -0
  177. package/src/ui/inline-panel/panel-selection.ts +157 -0
  178. package/src/ui/inline-panel/panel-store.ts +111 -0
  179. package/src/ui/inline-panel/view-session-store.ts +36 -0
  180. package/src/ui/keybinding-map.ts +54 -13
  181. package/src/ui/pi-ui-compat.ts +9 -0
  182. package/src/ui/powerbar-publisher.ts +52 -1
  183. package/src/ui/run-dashboard.ts +31 -5
  184. package/src/ui/run-snapshot-cache.ts +57 -30
  185. package/src/ui/snapshot-types.ts +6 -1
  186. package/src/ui/widget/index.ts +176 -22
  187. package/src/ui/widget/task-list.ts +198 -0
  188. package/src/ui/widget/widget-formatters.ts +240 -4
  189. package/src/ui/widget/widget-renderer.ts +243 -38
  190. package/src/ui/widget/widget-types.ts +11 -0
  191. package/src/utils/child-process-shield.ts +106 -0
  192. package/src/utils/file-coalescer.ts +0 -4
  193. package/src/utils/fs-errno.ts +66 -0
  194. package/src/utils/fs-watch.ts +1 -1
  195. package/src/utils/internal-error.ts +3 -1
  196. package/src/utils/paths.ts +11 -3
  197. package/src/utils/redaction.ts +7 -0
  198. package/src/utils/safe-abort.ts +45 -0
  199. package/src/utils/task-name-generator.ts +1 -8
  200. package/src/workflows/discover-workflows.ts +20 -2
  201. package/src/workflows/validate-workflow.ts +7 -1
  202. package/src/workflows/workflow-config.ts +17 -0
  203. package/src/workflows/workflow-serializer.ts +3 -0
  204. package/src/worktree/worktree-manager.ts +22 -0
  205. package/workflows/default.workflow.md +36 -26
  206. package/workflows/strict-fast-fix.workflow.md +26 -0
  207. package/src/agents/agent-search.ts +0 -98
  208. package/src/benchmark/benchmark-runner.ts +0 -313
  209. package/src/benchmark/feedback-loop.ts +0 -73
  210. package/src/config/resilient-parser.ts +0 -117
  211. package/src/extension/crew-vibes/cat-frames.ts +0 -18
  212. package/src/extension/result-watcher.ts +0 -139
  213. package/src/observability/exporters/prometheus-exporter.ts +0 -54
  214. package/src/observability/metric-retention.ts +0 -64
  215. package/src/runtime/compaction/compaction-summary.ts +0 -278
  216. package/src/runtime/errors/crew-errors.ts +0 -162
  217. package/src/runtime/live-session/intercom-bridge.ts +0 -187
  218. package/src/runtime/loop-gates.ts +0 -128
  219. package/src/runtime/metric-parser.ts +0 -36
  220. package/src/runtime/output/stream-preview.ts +0 -184
  221. package/src/runtime/output/tool-progress.ts +0 -278
  222. package/src/runtime/phase-tracker.ts +0 -385
  223. package/src/runtime/pipeline-runner.ts +0 -523
  224. package/src/runtime/process/process-lifecycle.ts +0 -491
  225. package/src/runtime/recovery/retry-runner.ts +0 -330
  226. package/src/runtime/run-drift.ts +0 -219
  227. package/src/runtime/task-quality.ts +0 -199
  228. package/src/runtime/task-runner/run-projection.ts +0 -128
  229. package/src/runtime/verification/post-checks.ts +0 -142
  230. package/src/state/coordination/schedule.ts +0 -166
  231. package/src/state/event-log/jsonl-writer.ts +0 -115
  232. package/src/state/hook-instinct-bridge.ts +0 -94
  233. package/src/state/hook-integrations.ts +0 -51
  234. package/src/state/session-state-map.ts +0 -51
  235. package/src/state/stores/blob-store.ts +0 -308
  236. package/src/state/stores/instinct-store.ts +0 -275
  237. package/src/state/stores/observation-store.ts +0 -176
  238. package/src/state/tiered-eval.ts +0 -480
  239. package/src/state/types-eval.ts +0 -58
  240. package/src/tools/safe-bash-extension.ts +0 -54
  241. package/src/tools/safe-bash.ts +0 -505
  242. package/src/ui/agent-management-overlay.ts +0 -160
  243. package/src/ui/crew-footer.ts +0 -102
  244. package/src/ui/crew-select-list.ts +0 -114
  245. package/src/ui/dashboard-panes/capability-pane.ts +0 -77
  246. package/src/ui/transcript-entries.ts +0 -256
  247. package/src/utils/conflict-detect.ts +0 -721
  248. package/src/utils/fingerprint.ts +0 -180
  249. package/src/utils/gh-protocol.ts +0 -556
  250. package/src/utils/project-detector.ts +0 -160
  251. package/src/utils/sse-parser.ts +0 -131
  252. package/src/workflows/cost-estimator.ts +0 -34
  253. 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
- }