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.
Files changed (162) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +27 -0
  3. package/README.md +5 -0
  4. package/agents/analyst.md +11 -11
  5. package/agents/critic.md +11 -11
  6. package/agents/executor.md +11 -11
  7. package/agents/explorer.md +11 -11
  8. package/agents/planner.md +11 -11
  9. package/agents/reviewer.md +11 -11
  10. package/agents/security-reviewer.md +11 -11
  11. package/agents/test-engineer.md +11 -11
  12. package/agents/verifier.md +11 -11
  13. package/agents/writer.md +11 -11
  14. package/docs/refactor-tasks-phase3.md +394 -394
  15. package/docs/refactor-tasks-phase4.md +564 -564
  16. package/docs/refactor-tasks-phase5.md +402 -402
  17. package/docs/refactor-tasks-phase6.md +662 -662
  18. package/docs/research-extension-examples.md +297 -297
  19. package/docs/research-extension-system.md +324 -324
  20. package/docs/research-optimization-plan.md +548 -548
  21. package/docs/research-pi-coding-agent.md +357 -357
  22. package/docs/research-source-pi-crew-reference.md +174 -174
  23. package/docs/resource-formats.md +10 -8
  24. package/docs/runtime-flow.md +148 -148
  25. package/docs/source-runtime-refactor-map.md +83 -83
  26. package/docs/usage.md +6 -0
  27. package/index.ts +6 -6
  28. package/package.json +3 -3
  29. package/schema.json +2 -2
  30. package/src/agents/agent-serializer.ts +34 -34
  31. package/src/config/config.ts +8 -4
  32. package/src/extension/cross-extension-rpc.ts +82 -82
  33. package/src/extension/import-index.ts +18 -2
  34. package/src/extension/register.ts +11 -1
  35. package/src/extension/registration/compaction-guard.ts +125 -125
  36. package/src/extension/registration/subagent-helpers.ts +30 -6
  37. package/src/extension/registration/subagent-tools.ts +8 -3
  38. package/src/extension/result-watcher.ts +98 -98
  39. package/src/extension/run-import.ts +12 -2
  40. package/src/extension/run-index.ts +12 -2
  41. package/src/extension/run-maintenance.ts +24 -24
  42. package/src/extension/team-tool/api.ts +54 -14
  43. package/src/extension/team-tool/cancel.ts +31 -31
  44. package/src/extension/team-tool/doctor.ts +179 -179
  45. package/src/extension/team-tool/inspect.ts +41 -41
  46. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  47. package/src/extension/team-tool/plan.ts +19 -19
  48. package/src/extension/team-tool/status.ts +73 -73
  49. package/src/observability/correlation.ts +35 -35
  50. package/src/observability/event-to-metric.ts +54 -54
  51. package/src/observability/exporters/adapter.ts +24 -24
  52. package/src/observability/exporters/otlp-exporter.ts +65 -65
  53. package/src/observability/exporters/prometheus-exporter.ts +47 -47
  54. package/src/observability/metric-registry.ts +72 -72
  55. package/src/observability/metric-retention.ts +46 -46
  56. package/src/observability/metric-sink.ts +51 -51
  57. package/src/observability/metrics-primitives.ts +166 -166
  58. package/src/prompt/prompt-runtime.ts +68 -68
  59. package/src/runtime/agent-control.ts +64 -64
  60. package/src/runtime/agent-memory.ts +72 -72
  61. package/src/runtime/agent-observability.ts +114 -113
  62. package/src/runtime/async-marker.ts +26 -26
  63. package/src/runtime/background-runner.ts +53 -53
  64. package/src/runtime/crash-recovery.ts +56 -56
  65. package/src/runtime/crew-agent-records.ts +54 -9
  66. package/src/runtime/crew-agent-runtime.ts +58 -58
  67. package/src/runtime/deadletter.ts +36 -36
  68. package/src/runtime/direct-run.ts +35 -35
  69. package/src/runtime/foreground-control.ts +82 -82
  70. package/src/runtime/green-contract.ts +46 -46
  71. package/src/runtime/group-join.ts +88 -88
  72. package/src/runtime/heartbeat-gradient.ts +28 -28
  73. package/src/runtime/heartbeat-watcher.ts +80 -80
  74. package/src/runtime/live-agent-control.ts +87 -78
  75. package/src/runtime/live-agent-manager.ts +85 -85
  76. package/src/runtime/live-control-realtime.ts +36 -36
  77. package/src/runtime/live-session-runtime.ts +299 -299
  78. package/src/runtime/manifest-cache.ts +248 -212
  79. package/src/runtime/model-fallback.ts +261 -261
  80. package/src/runtime/parallel-research.ts +44 -44
  81. package/src/runtime/parallel-utils.ts +99 -99
  82. package/src/runtime/pi-json-output.ts +111 -111
  83. package/src/runtime/policy-engine.ts +78 -78
  84. package/src/runtime/post-exit-stdio-guard.ts +86 -86
  85. package/src/runtime/process-status.ts +56 -56
  86. package/src/runtime/progress-event-coalescer.ts +43 -43
  87. package/src/runtime/recovery-recipes.ts +74 -74
  88. package/src/runtime/retry-executor.ts +59 -59
  89. package/src/runtime/role-permission.ts +39 -39
  90. package/src/runtime/session-usage.ts +79 -79
  91. package/src/runtime/sidechain-output.ts +28 -28
  92. package/src/runtime/subagent-manager.ts +80 -12
  93. package/src/runtime/task-display.ts +38 -38
  94. package/src/runtime/task-output-context.ts +127 -106
  95. package/src/runtime/task-runner/live-executor.ts +98 -98
  96. package/src/runtime/task-runner/progress.ts +111 -111
  97. package/src/runtime/task-runner/result-utils.ts +14 -14
  98. package/src/runtime/task-runner/state-helpers.ts +22 -22
  99. package/src/runtime/team-runner.ts +1 -1
  100. package/src/runtime/worker-heartbeat.ts +21 -21
  101. package/src/runtime/worker-startup.ts +57 -57
  102. package/src/schema/config-schema.ts +21 -21
  103. package/src/schema/team-tool-schema.ts +100 -100
  104. package/src/state/artifact-store.ts +122 -108
  105. package/src/state/contracts.ts +105 -105
  106. package/src/state/jsonl-writer.ts +77 -77
  107. package/src/state/mailbox.ts +67 -22
  108. package/src/state/state-store.ts +36 -5
  109. package/src/state/task-claims.ts +42 -42
  110. package/src/state/usage.ts +29 -29
  111. package/src/subagents/async-entry.ts +1 -1
  112. package/src/subagents/index.ts +3 -3
  113. package/src/subagents/live/control.ts +1 -1
  114. package/src/subagents/live/manager.ts +1 -1
  115. package/src/subagents/live/realtime.ts +1 -1
  116. package/src/subagents/live/session-runtime.ts +1 -1
  117. package/src/subagents/manager.ts +1 -1
  118. package/src/subagents/spawn.ts +1 -1
  119. package/src/teams/discover-teams.ts +27 -5
  120. package/src/teams/team-serializer.ts +38 -36
  121. package/src/types/diff.d.ts +18 -18
  122. package/src/ui/crew-footer.ts +101 -101
  123. package/src/ui/crew-select-list.ts +111 -111
  124. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  125. package/src/ui/dynamic-border.ts +25 -25
  126. package/src/ui/layout-primitives.ts +106 -106
  127. package/src/ui/loaders.ts +158 -158
  128. package/src/ui/mascot.ts +441 -441
  129. package/src/ui/render-diff.ts +119 -119
  130. package/src/ui/run-dashboard.ts +5 -2
  131. package/src/ui/run-snapshot-cache.ts +19 -8
  132. package/src/ui/spinner.ts +17 -17
  133. package/src/ui/status-colors.ts +54 -54
  134. package/src/ui/syntax-highlight.ts +116 -116
  135. package/src/ui/transcript-viewer.ts +15 -1
  136. package/src/utils/completion-dedupe.ts +63 -63
  137. package/src/utils/file-coalescer.ts +84 -84
  138. package/src/utils/frontmatter.ts +36 -36
  139. package/src/utils/fs-watch.ts +31 -31
  140. package/src/utils/git.ts +262 -262
  141. package/src/utils/ids.ts +12 -12
  142. package/src/utils/names.ts +26 -26
  143. package/src/utils/paths.ts +3 -2
  144. package/src/utils/safe-paths.ts +34 -0
  145. package/src/utils/sleep.ts +32 -32
  146. package/src/utils/timings.ts +31 -31
  147. package/src/utils/visual.ts +159 -159
  148. package/src/workflows/discover-workflows.ts +30 -3
  149. package/src/workflows/validate-workflow.ts +40 -40
  150. package/src/worktree/branch-freshness.ts +45 -45
  151. package/teams/default.team.md +12 -12
  152. package/teams/fast-fix.team.md +11 -11
  153. package/teams/implementation.team.md +18 -18
  154. package/teams/parallel-research.team.md +14 -14
  155. package/teams/research.team.md +11 -11
  156. package/teams/review.team.md +12 -12
  157. package/workflows/default.workflow.md +29 -29
  158. package/workflows/fast-fix.workflow.md +22 -22
  159. package/workflows/implementation.workflow.md +38 -38
  160. package/workflows/parallel-research.workflow.md +46 -46
  161. package/workflows/research.workflow.md +22 -22
  162. package/workflows/review.workflow.md +30 -30
@@ -1,72 +1,72 @@
1
- import * as fs from "node:fs";
2
- import * as os from "node:os";
3
- import * as path from "node:path";
4
-
5
- export type AgentMemoryScope = "user" | "project" | "local";
6
- const MAX_MEMORY_LINES = 200;
7
-
8
- export function isUnsafeMemoryName(name: string): boolean {
9
- return !name || name.length > 128 || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
10
- }
11
-
12
- export function isSymlink(filePath: string): boolean {
13
- try {
14
- return fs.lstatSync(filePath).isSymbolicLink();
15
- } catch {
16
- return false;
17
- }
18
- }
19
-
20
- export function safeReadMemoryFile(filePath: string): string | undefined {
21
- if (!fs.existsSync(filePath) || isSymlink(filePath)) return undefined;
22
- try {
23
- return fs.readFileSync(filePath, "utf-8");
24
- } catch {
25
- return undefined;
26
- }
27
- }
28
-
29
- export function resolveMemoryDir(agentName: string, scope: AgentMemoryScope, cwd: string): string {
30
- if (isUnsafeMemoryName(agentName)) throw new Error(`Unsafe agent name for memory directory: ${agentName}`);
31
- if (scope === "user") return path.join(os.homedir(), ".pi", "agent-memory", agentName);
32
- if (scope === "project") return path.join(cwd, ".pi", "agent-memory", agentName);
33
- return path.join(cwd, ".pi", "agent-memory-local", agentName);
34
- }
35
-
36
- export function ensureMemoryDir(memoryDir: string): void {
37
- if (fs.existsSync(memoryDir)) {
38
- if (isSymlink(memoryDir)) throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
39
- return;
40
- }
41
- fs.mkdirSync(memoryDir, { recursive: true });
42
- }
43
-
44
- export function readMemoryIndex(memoryDir: string): string | undefined {
45
- if (isSymlink(memoryDir)) return undefined;
46
- const content = safeReadMemoryFile(path.join(memoryDir, "MEMORY.md"));
47
- if (content === undefined) return undefined;
48
- const lines = content.split(/\r?\n/);
49
- return lines.length > MAX_MEMORY_LINES ? `${lines.slice(0, MAX_MEMORY_LINES).join("\n")}\n... (truncated at 200 lines)` : content;
50
- }
51
-
52
- export function buildMemoryBlock(agentName: string, scope: AgentMemoryScope, cwd: string, writable: boolean): string {
53
- const memoryDir = resolveMemoryDir(agentName, scope, cwd);
54
- if (writable) ensureMemoryDir(memoryDir);
55
- const existing = readMemoryIndex(memoryDir);
56
- const mode = writable ? "read-write" : "read-only";
57
- return [
58
- `# Agent Memory (${mode})`,
59
- `Memory scope: ${scope}`,
60
- `Memory directory: ${memoryDir}`,
61
- writable ? "Use this persistent directory to maintain useful long-term notes for this agent." : "You may reference existing memory, but do not create or modify memory files.",
62
- "",
63
- existing ? `## Current MEMORY.md\n${existing}` : "No MEMORY.md exists yet.",
64
- writable ? [
65
- "",
66
- "## Memory Instructions",
67
- "- Keep MEMORY.md concise (under 200 lines); store details in separate linked files.",
68
- "- Reject stale memories; update or remove outdated notes.",
69
- "- Use safe relative filenames inside the memory directory only.",
70
- ].join("\n") : "",
71
- ].filter(Boolean).join("\n");
72
- }
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+
5
+ export type AgentMemoryScope = "user" | "project" | "local";
6
+ const MAX_MEMORY_LINES = 200;
7
+
8
+ export function isUnsafeMemoryName(name: string): boolean {
9
+ return !name || name.length > 128 || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
10
+ }
11
+
12
+ export function isSymlink(filePath: string): boolean {
13
+ try {
14
+ return fs.lstatSync(filePath).isSymbolicLink();
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ export function safeReadMemoryFile(filePath: string): string | undefined {
21
+ if (!fs.existsSync(filePath) || isSymlink(filePath)) return undefined;
22
+ try {
23
+ return fs.readFileSync(filePath, "utf-8");
24
+ } catch {
25
+ return undefined;
26
+ }
27
+ }
28
+
29
+ export function resolveMemoryDir(agentName: string, scope: AgentMemoryScope, cwd: string): string {
30
+ if (isUnsafeMemoryName(agentName)) throw new Error(`Unsafe agent name for memory directory: ${agentName}`);
31
+ if (scope === "user") return path.join(os.homedir(), ".pi", "agent-memory", agentName);
32
+ if (scope === "project") return path.join(cwd, ".pi", "agent-memory", agentName);
33
+ return path.join(cwd, ".pi", "agent-memory-local", agentName);
34
+ }
35
+
36
+ export function ensureMemoryDir(memoryDir: string): void {
37
+ if (fs.existsSync(memoryDir)) {
38
+ if (isSymlink(memoryDir)) throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
39
+ return;
40
+ }
41
+ fs.mkdirSync(memoryDir, { recursive: true });
42
+ }
43
+
44
+ export function readMemoryIndex(memoryDir: string): string | undefined {
45
+ if (isSymlink(memoryDir)) return undefined;
46
+ const content = safeReadMemoryFile(path.join(memoryDir, "MEMORY.md"));
47
+ if (content === undefined) return undefined;
48
+ const lines = content.split(/\r?\n/);
49
+ return lines.length > MAX_MEMORY_LINES ? `${lines.slice(0, MAX_MEMORY_LINES).join("\n")}\n... (truncated at 200 lines)` : content;
50
+ }
51
+
52
+ export function buildMemoryBlock(agentName: string, scope: AgentMemoryScope, cwd: string, writable: boolean): string {
53
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
54
+ if (writable) ensureMemoryDir(memoryDir);
55
+ const existing = readMemoryIndex(memoryDir);
56
+ const mode = writable ? "read-write" : "read-only";
57
+ return [
58
+ `# Agent Memory (${mode})`,
59
+ `Memory scope: ${scope}`,
60
+ `Memory directory: ${memoryDir}`,
61
+ writable ? "Use this persistent directory to maintain useful long-term notes for this agent." : "You may reference existing memory, but do not create or modify memory files.",
62
+ "",
63
+ existing ? `## Current MEMORY.md\n${existing}` : "No MEMORY.md exists yet.",
64
+ writable ? [
65
+ "",
66
+ "## Memory Instructions",
67
+ "- Keep MEMORY.md concise (under 200 lines); store details in separate linked files.",
68
+ "- Reject stale memories; update or remove outdated notes.",
69
+ "- Use safe relative filenames inside the memory directory only.",
70
+ ].join("\n") : "",
71
+ ].filter(Boolean).join("\n");
72
+ }
@@ -1,113 +1,114 @@
1
- import * as fs from "node:fs";
2
- import type { TeamRunManifest } from "../state/types.ts";
3
- import { agentOutputPath, readCrewAgents } from "./crew-agent-records.ts";
4
- import type { CrewAgentRecord } from "./crew-agent-runtime.ts";
5
-
6
- const TOOL_LABELS: Record<string, string> = {
7
- read: "reading",
8
- bash: "running command",
9
- edit: "editing",
10
- write: "writing",
11
- grep: "searching",
12
- find: "finding files",
13
- ls: "listing",
14
- };
15
-
16
- export interface TextTailResult {
17
- path: string;
18
- text: string;
19
- bytes: number;
20
- truncated: boolean;
21
- }
22
-
23
- export function readTextTail(filePath: string, maxBytes = 64_000): TextTailResult {
24
- if (!fs.existsSync(filePath)) return { path: filePath, text: "", bytes: 0, truncated: false };
25
- const stat = fs.statSync(filePath);
26
- const bytesToRead = Math.min(stat.size, Math.max(0, maxBytes));
27
- const fd = fs.openSync(filePath, "r");
28
- try {
29
- const buffer = Buffer.alloc(bytesToRead);
30
- fs.readSync(fd, buffer, 0, bytesToRead, stat.size - bytesToRead);
31
- return { path: filePath, text: buffer.toString("utf-8"), bytes: stat.size, truncated: stat.size > bytesToRead };
32
- } finally {
33
- fs.closeSync(fd);
34
- }
35
- }
36
-
37
- function compactDuration(ms: number | undefined): string | undefined {
38
- if (ms === undefined || !Number.isFinite(ms)) return undefined;
39
- if (ms < 1000) return `${Math.round(ms)}ms`;
40
- if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
41
- return `${Math.floor(ms / 60_000)}m${Math.floor((ms % 60_000) / 1000)}s`;
42
- }
43
-
44
- function ageBetween(start: string | undefined, end: string | undefined): string | undefined {
45
- if (!start) return undefined;
46
- const stop = end ? new Date(end).getTime() : Date.now();
47
- const ms = Math.max(0, stop - new Date(start).getTime());
48
- return compactDuration(ms);
49
- }
50
-
51
- function activityText(agent: CrewAgentRecord): string {
52
- const parts: string[] = [];
53
- if (agent.progress?.activityState) parts.push(agent.progress.activityState);
54
- if (agent.progress?.currentTool) parts.push(TOOL_LABELS[agent.progress.currentTool] ?? `tool=${agent.progress.currentTool}`);
55
- if (agent.toolUses !== undefined) parts.push(`tools=${agent.toolUses}`);
56
- if (agent.progress?.tokens !== undefined) parts.push(`tokens=${agent.progress.tokens}`);
57
- if (agent.progress?.turns !== undefined) parts.push(`turns=${agent.progress.turns}`);
58
- const duration = compactDuration(agent.progress?.durationMs) ?? ageBetween(agent.startedAt, agent.completedAt);
59
- if (duration) parts.push(duration);
60
- if (agent.progress?.failedTool) parts.push(`failedTool=${agent.progress.failedTool}`);
61
- if (agent.progress?.recentOutput?.length) parts.push(`last=${agent.progress.recentOutput.at(-1)}`);
62
- return parts.join(" ") || "idle";
63
- }
64
-
65
- function statusGlyph(status: CrewAgentRecord["status"]): string {
66
- if (status === "completed") return "✓";
67
- if (status === "failed") return "✗";
68
- if (status === "running") return "▶";
69
- if (status === "cancelled" || status === "stopped") return "■";
70
- return "·";
71
- }
72
-
73
- function outputWarning(agent: CrewAgentRecord): string {
74
- if (agent.status !== "completed") return "";
75
- if (!agent.outputPath || !fs.existsSync(agent.outputPath)) return " no-output";
76
- try {
77
- return fs.statSync(agent.outputPath).size === 0 ? " no-output" : "";
78
- } catch {
79
- return " no-output";
80
- }
81
- }
82
-
83
- function agentLine(agent: CrewAgentRecord): string {
84
- return `- ${statusGlyph(agent.status)} ${agent.taskId} ${agent.role} → ${agent.agent} · ${agent.status} · ${agent.runtime} · ${activityText(agent)}${outputWarning(agent)}${agent.error ? ` · error=${agent.error}` : ""}`;
85
- }
86
-
87
- export function buildAgentDashboard(manifest: TeamRunManifest): { text: string; groups: Record<string, CrewAgentRecord[]> } {
88
- const agents = readCrewAgents(manifest);
89
- const groups: Record<string, CrewAgentRecord[]> = {
90
- running: agents.filter((agent) => agent.status === "running"),
91
- queued: agents.filter((agent) => agent.status === "queued"),
92
- recent: agents.filter((agent) => agent.status !== "running" && agent.status !== "queued"),
93
- };
94
- const lines = [
95
- `Crew agents for ${manifest.runId}`,
96
- `Run: ${manifest.status} · ${manifest.team}/${manifest.workflow ?? "none"} · agents=${agents.length}`,
97
- `Counts: running=${groups.running.length}, queued=${groups.queued.length}, recent=${groups.recent.length}`,
98
- "",
99
- "## Running",
100
- ...(groups.running.length ? groups.running.map(agentLine) : ["- (none)"]),
101
- "",
102
- "## Queued",
103
- ...(groups.queued.length ? groups.queued.map(agentLine) : ["- (none)"]),
104
- "",
105
- "## Recent",
106
- ...(groups.recent.length ? groups.recent.slice(-10).map(agentLine) : ["- (none)"]),
107
- ];
108
- return { text: lines.join("\n"), groups };
109
- }
110
-
111
- export function readAgentOutput(manifest: TeamRunManifest, taskId: string, maxBytes?: number): TextTailResult {
112
- return readTextTail(agentOutputPath(manifest, taskId), maxBytes);
113
- }
1
+ import * as fs from "node:fs";
2
+ import type { TeamRunManifest } from "../state/types.ts";
3
+ import { agentOutputPath, readCrewAgents } from "./crew-agent-records.ts";
4
+ import type { CrewAgentRecord } from "./crew-agent-runtime.ts";
5
+
6
+ const TOOL_LABELS: Record<string, string> = {
7
+ read: "reading",
8
+ bash: "running command",
9
+ edit: "editing",
10
+ write: "writing",
11
+ grep: "searching",
12
+ find: "finding files",
13
+ ls: "listing",
14
+ };
15
+
16
+ export interface TextTailResult {
17
+ path: string;
18
+ text: string;
19
+ bytes: number;
20
+ truncated: boolean;
21
+ }
22
+
23
+ export function readTextTail(filePath: string, maxBytes = 64_000): TextTailResult {
24
+ if (!fs.existsSync(filePath)) return { path: filePath, text: "", bytes: 0, truncated: false };
25
+ const stat = fs.statSync(filePath);
26
+ const bytesToRead = Math.min(stat.size, Math.max(0, maxBytes));
27
+ const fd = fs.openSync(filePath, "r");
28
+ try {
29
+ const buffer = Buffer.alloc(bytesToRead);
30
+ fs.readSync(fd, buffer, 0, bytesToRead, stat.size - bytesToRead);
31
+ return { path: filePath, text: buffer.toString("utf-8"), bytes: stat.size, truncated: stat.size > bytesToRead };
32
+ } finally {
33
+ fs.closeSync(fd);
34
+ }
35
+ }
36
+
37
+ function compactDuration(ms: number | undefined): string | undefined {
38
+ if (ms === undefined || !Number.isFinite(ms)) return undefined;
39
+ if (ms < 1000) return `${Math.round(ms)}ms`;
40
+ if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
41
+ return `${Math.floor(ms / 60_000)}m${Math.floor((ms % 60_000) / 1000)}s`;
42
+ }
43
+
44
+ function ageBetween(start: string | undefined, end: string | undefined): string | undefined {
45
+ if (!start) return undefined;
46
+ const stop = end ? new Date(end).getTime() : Date.now();
47
+ const ms = Math.max(0, stop - new Date(start).getTime());
48
+ return compactDuration(ms);
49
+ }
50
+
51
+ function activityText(agent: CrewAgentRecord): string {
52
+ const parts: string[] = [];
53
+ if (agent.progress?.activityState) parts.push(agent.progress.activityState);
54
+ if (agent.progress?.currentTool) parts.push(TOOL_LABELS[agent.progress.currentTool] ?? `tool=${agent.progress.currentTool}`);
55
+ if (agent.toolUses !== undefined) parts.push(`tools=${agent.toolUses}`);
56
+ if (agent.progress?.tokens !== undefined) parts.push(`tokens=${agent.progress.tokens}`);
57
+ if (agent.progress?.turns !== undefined) parts.push(`turns=${agent.progress.turns}`);
58
+ const duration = compactDuration(agent.progress?.durationMs) ?? ageBetween(agent.startedAt, agent.completedAt);
59
+ if (duration) parts.push(duration);
60
+ if (agent.progress?.failedTool) parts.push(`failedTool=${agent.progress.failedTool}`);
61
+ if (agent.progress?.recentOutput?.length) parts.push(`last=${agent.progress.recentOutput.at(-1)}`);
62
+ return parts.join(" ") || "idle";
63
+ }
64
+
65
+ function statusGlyph(status: CrewAgentRecord["status"]): string {
66
+ if (status === "completed") return "✓";
67
+ if (status === "failed") return "✗";
68
+ if (status === "running") return "▶";
69
+ if (status === "cancelled" || status === "stopped") return "■";
70
+ return "·";
71
+ }
72
+
73
+ function outputWarning(manifest: TeamRunManifest, agent: CrewAgentRecord): string {
74
+ if (agent.status !== "completed") return "";
75
+ try {
76
+ const outputPath = agentOutputPath(manifest, agent.taskId);
77
+ if (!fs.existsSync(outputPath)) return " no-output";
78
+ return fs.statSync(outputPath).size === 0 ? " no-output" : "";
79
+ } catch {
80
+ return " no-output";
81
+ }
82
+ }
83
+
84
+ function agentLine(manifest: TeamRunManifest, agent: CrewAgentRecord): string {
85
+ return `- ${statusGlyph(agent.status)} ${agent.taskId} ${agent.role} → ${agent.agent} · ${agent.status} · ${agent.runtime} · ${activityText(agent)}${outputWarning(manifest, agent)}${agent.error ? ` · error=${agent.error}` : ""}`;
86
+ }
87
+
88
+ export function buildAgentDashboard(manifest: TeamRunManifest): { text: string; groups: Record<string, CrewAgentRecord[]> } {
89
+ const agents = readCrewAgents(manifest);
90
+ const groups: Record<string, CrewAgentRecord[]> = {
91
+ running: agents.filter((agent) => agent.status === "running"),
92
+ queued: agents.filter((agent) => agent.status === "queued"),
93
+ recent: agents.filter((agent) => agent.status !== "running" && agent.status !== "queued"),
94
+ };
95
+ const lines = [
96
+ `Crew agents for ${manifest.runId}`,
97
+ `Run: ${manifest.status} · ${manifest.team}/${manifest.workflow ?? "none"} · agents=${agents.length}`,
98
+ `Counts: running=${groups.running.length}, queued=${groups.queued.length}, recent=${groups.recent.length}`,
99
+ "",
100
+ "## Running",
101
+ ...(groups.running.length ? groups.running.map((agent) => agentLine(manifest, agent)) : ["- (none)"]),
102
+ "",
103
+ "## Queued",
104
+ ...(groups.queued.length ? groups.queued.map((agent) => agentLine(manifest, agent)) : ["- (none)"]),
105
+ "",
106
+ "## Recent",
107
+ ...(groups.recent.length ? groups.recent.slice(-10).map((agent) => agentLine(manifest, agent)) : ["- (none)"]),
108
+ ];
109
+ return { text: lines.join("\n"), groups };
110
+ }
111
+
112
+ export function readAgentOutput(manifest: TeamRunManifest, taskId: string, maxBytes?: number): TextTailResult {
113
+ return readTextTail(agentOutputPath(manifest, taskId), maxBytes);
114
+ }
@@ -1,26 +1,26 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import { atomicWriteJson } from "../state/atomic-write.ts";
4
- import type { TeamRunManifest } from "../state/types.ts";
5
-
6
- export interface AsyncStartMarker {
7
- pid: number;
8
- startedAt: string;
9
- }
10
-
11
- export function asyncStartMarkerPath(manifest: Pick<TeamRunManifest, "stateRoot">): string {
12
- return path.join(manifest.stateRoot, "async.pid");
13
- }
14
-
15
- export function writeAsyncStartMarker(manifest: Pick<TeamRunManifest, "stateRoot">, marker: AsyncStartMarker): void {
16
- atomicWriteJson(asyncStartMarkerPath(manifest), marker);
17
- }
18
-
19
- export function hasAsyncStartMarker(manifest: Pick<TeamRunManifest, "stateRoot">): boolean {
20
- try {
21
- const raw = JSON.parse(fs.readFileSync(asyncStartMarkerPath(manifest), "utf-8")) as Partial<AsyncStartMarker>;
22
- return typeof raw.pid === "number" && Number.isInteger(raw.pid) && raw.pid > 0 && typeof raw.startedAt === "string" && raw.startedAt.length > 0;
23
- } catch {
24
- return false;
25
- }
26
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { atomicWriteJson } from "../state/atomic-write.ts";
4
+ import type { TeamRunManifest } from "../state/types.ts";
5
+
6
+ export interface AsyncStartMarker {
7
+ pid: number;
8
+ startedAt: string;
9
+ }
10
+
11
+ export function asyncStartMarkerPath(manifest: Pick<TeamRunManifest, "stateRoot">): string {
12
+ return path.join(manifest.stateRoot, "async.pid");
13
+ }
14
+
15
+ export function writeAsyncStartMarker(manifest: Pick<TeamRunManifest, "stateRoot">, marker: AsyncStartMarker): void {
16
+ atomicWriteJson(asyncStartMarkerPath(manifest), marker);
17
+ }
18
+
19
+ export function hasAsyncStartMarker(manifest: Pick<TeamRunManifest, "stateRoot">): boolean {
20
+ try {
21
+ const raw = JSON.parse(fs.readFileSync(asyncStartMarkerPath(manifest), "utf-8")) as Partial<AsyncStartMarker>;
22
+ return typeof raw.pid === "number" && Number.isInteger(raw.pid) && raw.pid > 0 && typeof raw.startedAt === "string" && raw.startedAt.length > 0;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
@@ -1,53 +1,53 @@
1
- import { allAgents, discoverAgents } from "../agents/discover-agents.ts";
2
- import { allTeams, discoverTeams } from "../teams/discover-teams.ts";
3
- import { appendEvent } from "../state/event-log.ts";
4
- import { loadRunManifestById, updateRunStatus } from "../state/state-store.ts";
5
- import { allWorkflows, discoverWorkflows } from "../workflows/discover-workflows.ts";
6
- import { loadConfig } from "../config/config.ts";
7
- import { executeTeamRun } from "./team-runner.ts";
8
- import { resolveCrewRuntime } from "./runtime-resolver.ts";
9
- import { directTeamAndWorkflowFromRun } from "./direct-run.ts";
10
- import { expandParallelResearchWorkflow } from "./parallel-research.ts";
11
- import { writeAsyncStartMarker } from "./async-marker.ts";
12
-
13
- function argValue(name: string): string | undefined {
14
- const index = process.argv.indexOf(name);
15
- if (index === -1) return undefined;
16
- return process.argv[index + 1];
17
- }
18
-
19
- async function main(): Promise<void> {
20
- const cwd = argValue("--cwd");
21
- const runId = argValue("--run-id");
22
- if (!cwd || !runId) throw new Error("Usage: background-runner.ts --cwd <cwd> --run-id <runId>");
23
-
24
- const loaded = loadRunManifestById(cwd, runId);
25
- if (!loaded) throw new Error(`Run '${runId}' not found.`);
26
- let { manifest, tasks } = loaded;
27
- appendEvent(manifest.eventsPath, { type: "async.started", runId: manifest.runId, data: { pid: process.pid } });
28
- writeAsyncStartMarker(manifest, { pid: process.pid, startedAt: new Date().toISOString() });
29
-
30
- try {
31
- const agents = allAgents(discoverAgents(cwd));
32
- const direct = directTeamAndWorkflowFromRun(manifest, tasks, agents);
33
- const team = direct?.team ?? allTeams(discoverTeams(cwd)).find((candidate) => candidate.name === manifest.team);
34
- if (!team) throw new Error(`Team '${manifest.team}' not found.`);
35
- const baseWorkflow = direct?.workflow ?? allWorkflows(discoverWorkflows(cwd)).find((candidate) => candidate.name === manifest.workflow);
36
- if (!baseWorkflow) throw new Error(`Workflow '${manifest.workflow ?? ""}' not found.`);
37
- const workflow = expandParallelResearchWorkflow(baseWorkflow, cwd);
38
- const loadedConfig = loadConfig(cwd);
39
- const runtime = await resolveCrewRuntime(loadedConfig.config);
40
- const executeWorkers = runtime.kind !== "scaffold";
41
- const result = await executeTeamRun({ manifest, tasks, team, workflow, agents, executeWorkers, limits: loadedConfig.config.limits, runtime, runtimeConfig: loadedConfig.config.runtime });
42
- manifest = result.manifest;
43
- tasks = result.tasks;
44
- appendEvent(manifest.eventsPath, { type: "async.completed", runId: manifest.runId, data: { status: manifest.status, tasks: tasks.length } });
45
- } catch (error) {
46
- const message = error instanceof Error ? error.message : String(error);
47
- manifest = updateRunStatus(manifest, "failed", message);
48
- appendEvent(manifest.eventsPath, { type: "async.failed", runId: manifest.runId, message });
49
- process.exitCode = 1;
50
- }
51
- }
52
-
53
- await main();
1
+ import { allAgents, discoverAgents } from "../agents/discover-agents.ts";
2
+ import { allTeams, discoverTeams } from "../teams/discover-teams.ts";
3
+ import { appendEvent } from "../state/event-log.ts";
4
+ import { loadRunManifestById, updateRunStatus } from "../state/state-store.ts";
5
+ import { allWorkflows, discoverWorkflows } from "../workflows/discover-workflows.ts";
6
+ import { loadConfig } from "../config/config.ts";
7
+ import { executeTeamRun } from "./team-runner.ts";
8
+ import { resolveCrewRuntime } from "./runtime-resolver.ts";
9
+ import { directTeamAndWorkflowFromRun } from "./direct-run.ts";
10
+ import { expandParallelResearchWorkflow } from "./parallel-research.ts";
11
+ import { writeAsyncStartMarker } from "./async-marker.ts";
12
+
13
+ function argValue(name: string): string | undefined {
14
+ const index = process.argv.indexOf(name);
15
+ if (index === -1) return undefined;
16
+ return process.argv[index + 1];
17
+ }
18
+
19
+ async function main(): Promise<void> {
20
+ const cwd = argValue("--cwd");
21
+ const runId = argValue("--run-id");
22
+ if (!cwd || !runId) throw new Error("Usage: background-runner.ts --cwd <cwd> --run-id <runId>");
23
+
24
+ const loaded = loadRunManifestById(cwd, runId);
25
+ if (!loaded) throw new Error(`Run '${runId}' not found.`);
26
+ let { manifest, tasks } = loaded;
27
+ appendEvent(manifest.eventsPath, { type: "async.started", runId: manifest.runId, data: { pid: process.pid } });
28
+ writeAsyncStartMarker(manifest, { pid: process.pid, startedAt: new Date().toISOString() });
29
+
30
+ try {
31
+ const agents = allAgents(discoverAgents(cwd));
32
+ const direct = directTeamAndWorkflowFromRun(manifest, tasks, agents);
33
+ const team = direct?.team ?? allTeams(discoverTeams(cwd)).find((candidate) => candidate.name === manifest.team);
34
+ if (!team) throw new Error(`Team '${manifest.team}' not found.`);
35
+ const baseWorkflow = direct?.workflow ?? allWorkflows(discoverWorkflows(cwd)).find((candidate) => candidate.name === manifest.workflow);
36
+ if (!baseWorkflow) throw new Error(`Workflow '${manifest.workflow ?? ""}' not found.`);
37
+ const workflow = expandParallelResearchWorkflow(baseWorkflow, cwd);
38
+ const loadedConfig = loadConfig(cwd);
39
+ const runtime = await resolveCrewRuntime(loadedConfig.config);
40
+ const executeWorkers = runtime.kind !== "scaffold";
41
+ const result = await executeTeamRun({ manifest, tasks, team, workflow, agents, executeWorkers, limits: loadedConfig.config.limits, runtime, runtimeConfig: loadedConfig.config.runtime });
42
+ manifest = result.manifest;
43
+ tasks = result.tasks;
44
+ appendEvent(manifest.eventsPath, { type: "async.completed", runId: manifest.runId, data: { status: manifest.status, tasks: tasks.length } });
45
+ } catch (error) {
46
+ const message = error instanceof Error ? error.message : String(error);
47
+ manifest = updateRunStatus(manifest, "failed", message);
48
+ appendEvent(manifest.eventsPath, { type: "async.failed", runId: manifest.runId, message });
49
+ process.exitCode = 1;
50
+ }
51
+ }
52
+
53
+ await main();