pi-crew 0.1.30 → 0.1.32

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 (159) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +80 -27
  3. package/agents/analyst.md +11 -11
  4. package/agents/critic.md +11 -11
  5. package/agents/executor.md +11 -11
  6. package/agents/explorer.md +11 -11
  7. package/agents/planner.md +11 -11
  8. package/agents/reviewer.md +11 -11
  9. package/agents/security-reviewer.md +11 -11
  10. package/agents/test-engineer.md +11 -11
  11. package/agents/verifier.md +11 -11
  12. package/agents/writer.md +11 -11
  13. package/docs/architecture.md +173 -164
  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 -0
  19. package/docs/research-extension-system.md +324 -0
  20. package/docs/research-optimization-plan.md +548 -0
  21. package/docs/research-pi-coding-agent.md +357 -0
  22. package/docs/resource-formats.md +4 -3
  23. package/docs/runtime-flow.md +148 -148
  24. package/docs/source-runtime-refactor-map.md +83 -83
  25. package/docs/usage.md +3 -3
  26. package/index.ts +6 -6
  27. package/package.json +1 -1
  28. package/schema.json +53 -1
  29. package/skills/git-master/SKILL.md +24 -19
  30. package/skills/read-only-explorer/SKILL.md +26 -21
  31. package/skills/safe-bash/SKILL.md +21 -16
  32. package/skills/task-packet/SKILL.md +28 -23
  33. package/skills/verify-evidence/SKILL.md +27 -22
  34. package/src/agents/agent-serializer.ts +34 -34
  35. package/src/agents/discover-agents.ts +102 -102
  36. package/src/config/config.ts +14 -1
  37. package/src/config/defaults.ts +3 -2
  38. package/src/extension/cross-extension-rpc.ts +82 -82
  39. package/src/extension/import-index.ts +4 -3
  40. package/src/extension/management.ts +2 -2
  41. package/src/extension/project-init.ts +9 -7
  42. package/src/extension/register.ts +63 -0
  43. package/src/extension/registration/artifact-cleanup.ts +15 -14
  44. package/src/extension/registration/commands.ts +208 -208
  45. package/src/extension/registration/compaction-guard.ts +125 -0
  46. package/src/extension/registration/subagent-tools.ts +27 -8
  47. package/src/extension/registration/team-tool.ts +61 -44
  48. package/src/extension/result-watcher.ts +98 -98
  49. package/src/extension/run-import.ts +4 -4
  50. package/src/extension/run-index.ts +14 -14
  51. package/src/extension/run-maintenance.ts +24 -24
  52. package/src/extension/team-tool/api.ts +3 -0
  53. package/src/extension/team-tool/cancel.ts +31 -31
  54. package/src/extension/team-tool/doctor.ts +179 -178
  55. package/src/extension/team-tool/inspect.ts +41 -41
  56. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  57. package/src/extension/team-tool/plan.ts +19 -19
  58. package/src/extension/team-tool/status.ts +73 -73
  59. package/src/prompt/prompt-runtime.ts +68 -68
  60. package/src/runtime/agent-control.ts +64 -64
  61. package/src/runtime/agent-memory.ts +72 -72
  62. package/src/runtime/agent-observability.ts +113 -113
  63. package/src/runtime/async-marker.ts +26 -26
  64. package/src/runtime/background-runner.ts +53 -53
  65. package/src/runtime/crew-agent-runtime.ts +58 -58
  66. package/src/runtime/direct-run.ts +35 -35
  67. package/src/runtime/foreground-control.ts +82 -82
  68. package/src/runtime/green-contract.ts +46 -46
  69. package/src/runtime/group-join.ts +88 -88
  70. package/src/runtime/live-agent-control.ts +78 -78
  71. package/src/runtime/live-agent-manager.ts +85 -85
  72. package/src/runtime/live-control-realtime.ts +36 -36
  73. package/src/runtime/live-session-runtime.ts +299 -299
  74. package/src/runtime/manifest-cache.ts +212 -214
  75. package/src/runtime/model-fallback.ts +261 -261
  76. package/src/runtime/parallel-research.ts +44 -44
  77. package/src/runtime/parallel-utils.ts +99 -99
  78. package/src/runtime/pi-json-output.ts +111 -111
  79. package/src/runtime/pi-spawn.ts +96 -96
  80. package/src/runtime/policy-engine.ts +78 -78
  81. package/src/runtime/post-exit-stdio-guard.ts +86 -86
  82. package/src/runtime/process-status.ts +56 -56
  83. package/src/runtime/progress-event-coalescer.ts +43 -43
  84. package/src/runtime/recovery-recipes.ts +74 -74
  85. package/src/runtime/role-permission.ts +39 -39
  86. package/src/runtime/session-usage.ts +79 -79
  87. package/src/runtime/sidechain-output.ts +28 -28
  88. package/src/runtime/subagent-manager.ts +29 -2
  89. package/src/runtime/task-display.ts +38 -38
  90. package/src/runtime/task-output-context.ts +106 -106
  91. package/src/runtime/task-packet.ts +84 -84
  92. package/src/runtime/task-runner/live-executor.ts +98 -98
  93. package/src/runtime/task-runner/progress.ts +111 -111
  94. package/src/runtime/task-runner/prompt-builder.ts +72 -72
  95. package/src/runtime/task-runner/result-utils.ts +14 -14
  96. package/src/runtime/task-runner/state-helpers.ts +22 -22
  97. package/src/runtime/worker-heartbeat.ts +21 -21
  98. package/src/runtime/worker-startup.ts +57 -57
  99. package/src/schema/config-schema.ts +12 -0
  100. package/src/schema/team-tool-schema.ts +100 -100
  101. package/src/state/artifact-store.ts +108 -108
  102. package/src/state/contracts.ts +105 -105
  103. package/src/state/jsonl-writer.ts +77 -77
  104. package/src/state/state-store.ts +8 -9
  105. package/src/state/task-claims.ts +42 -42
  106. package/src/state/types.ts +180 -180
  107. package/src/state/usage.ts +29 -29
  108. package/src/subagents/async-entry.ts +1 -1
  109. package/src/subagents/index.ts +3 -3
  110. package/src/subagents/live/control.ts +1 -1
  111. package/src/subagents/live/manager.ts +1 -1
  112. package/src/subagents/live/realtime.ts +1 -1
  113. package/src/subagents/live/session-runtime.ts +1 -1
  114. package/src/subagents/manager.ts +1 -1
  115. package/src/subagents/spawn.ts +1 -1
  116. package/src/teams/discover-teams.ts +2 -2
  117. package/src/teams/team-serializer.ts +36 -36
  118. package/src/types/diff.d.ts +18 -0
  119. package/src/ui/crew-footer.ts +101 -101
  120. package/src/ui/crew-select-list.ts +111 -111
  121. package/src/ui/crew-widget.ts +285 -285
  122. package/src/ui/dynamic-border.ts +25 -25
  123. package/src/ui/layout-primitives.ts +106 -106
  124. package/src/ui/loaders.ts +158 -158
  125. package/src/ui/mascot.ts +441 -441
  126. package/src/ui/powerbar-publisher.ts +94 -94
  127. package/src/ui/render-diff.ts +119 -119
  128. package/src/ui/run-dashboard.ts +372 -372
  129. package/src/ui/status-colors.ts +54 -54
  130. package/src/ui/syntax-highlight.ts +116 -116
  131. package/src/ui/transcript-viewer.ts +302 -302
  132. package/src/utils/completion-dedupe.ts +63 -63
  133. package/src/utils/file-coalescer.ts +84 -84
  134. package/src/utils/frontmatter.ts +36 -36
  135. package/src/utils/fs-watch.ts +31 -31
  136. package/src/utils/git.ts +262 -262
  137. package/src/utils/ids.ts +12 -12
  138. package/src/utils/names.ts +26 -26
  139. package/src/utils/paths.ts +34 -7
  140. package/src/utils/sleep.ts +32 -32
  141. package/src/utils/timings.ts +31 -31
  142. package/src/utils/visual.ts +159 -159
  143. package/src/workflows/discover-workflows.ts +2 -2
  144. package/src/workflows/validate-workflow.ts +40 -40
  145. package/src/worktree/branch-freshness.ts +45 -45
  146. package/src/worktree/cleanup.ts +71 -69
  147. package/src/worktree/worktree-manager.ts +3 -1
  148. package/teams/default.team.md +12 -12
  149. package/teams/fast-fix.team.md +11 -11
  150. package/teams/implementation.team.md +18 -18
  151. package/teams/parallel-research.team.md +14 -14
  152. package/teams/research.team.md +11 -11
  153. package/teams/review.team.md +12 -12
  154. package/workflows/default.workflow.md +29 -29
  155. package/workflows/fast-fix.workflow.md +22 -22
  156. package/workflows/implementation.workflow.md +38 -38
  157. package/workflows/parallel-research.workflow.md +46 -46
  158. package/workflows/research.workflow.md +22 -22
  159. package/workflows/review.workflow.md +30 -30
@@ -1,113 +1,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(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(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,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();
@@ -1,58 +1,58 @@
1
- import type { TeamTaskStatus } from "../state/contracts.ts";
2
- import type { ModelRoutingState, UsageState } from "../state/types.ts";
3
-
4
- export type CrewRuntimeKind = "scaffold" | "child-process" | "live-session";
5
- export type CrewAgentStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | "stopped";
6
-
7
- export interface CrewAgentRecentTool {
8
- tool: string;
9
- args?: string;
10
- endedAt: string;
11
- }
12
-
13
- export interface CrewAgentProgress {
14
- currentTool?: string;
15
- currentToolArgs?: string;
16
- currentToolStartedAt?: string;
17
- recentTools: CrewAgentRecentTool[];
18
- recentOutput: string[];
19
- toolCount: number;
20
- tokens?: number;
21
- turns?: number;
22
- durationMs?: number;
23
- lastActivityAt?: string;
24
- activityState?: "active" | "needs_attention" | "stale";
25
- failedTool?: string;
26
- }
27
-
28
- export interface CrewAgentRecord {
29
- id: string;
30
- runId: string;
31
- taskId: string;
32
- agent: string;
33
- role: string;
34
- runtime: CrewRuntimeKind;
35
- status: CrewAgentStatus;
36
- startedAt: string;
37
- completedAt?: string;
38
- resultArtifactPath?: string;
39
- transcriptPath?: string;
40
- statusPath?: string;
41
- eventsPath?: string;
42
- outputPath?: string;
43
- toolUses?: number;
44
- jsonEvents?: number;
45
- model?: string;
46
- routing?: ModelRoutingState;
47
- usage?: UsageState;
48
- progress?: CrewAgentProgress;
49
- error?: string;
50
- }
51
-
52
- export function taskStatusToAgentStatus(status: TeamTaskStatus): CrewAgentStatus {
53
- if (status === "completed") return "completed";
54
- if (status === "failed") return "failed";
55
- if (status === "cancelled" || status === "skipped") return "cancelled";
56
- if (status === "running") return "running";
57
- return "queued";
58
- }
1
+ import type { TeamTaskStatus } from "../state/contracts.ts";
2
+ import type { ModelRoutingState, UsageState } from "../state/types.ts";
3
+
4
+ export type CrewRuntimeKind = "scaffold" | "child-process" | "live-session";
5
+ export type CrewAgentStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | "stopped";
6
+
7
+ export interface CrewAgentRecentTool {
8
+ tool: string;
9
+ args?: string;
10
+ endedAt: string;
11
+ }
12
+
13
+ export interface CrewAgentProgress {
14
+ currentTool?: string;
15
+ currentToolArgs?: string;
16
+ currentToolStartedAt?: string;
17
+ recentTools: CrewAgentRecentTool[];
18
+ recentOutput: string[];
19
+ toolCount: number;
20
+ tokens?: number;
21
+ turns?: number;
22
+ durationMs?: number;
23
+ lastActivityAt?: string;
24
+ activityState?: "active" | "needs_attention" | "stale";
25
+ failedTool?: string;
26
+ }
27
+
28
+ export interface CrewAgentRecord {
29
+ id: string;
30
+ runId: string;
31
+ taskId: string;
32
+ agent: string;
33
+ role: string;
34
+ runtime: CrewRuntimeKind;
35
+ status: CrewAgentStatus;
36
+ startedAt: string;
37
+ completedAt?: string;
38
+ resultArtifactPath?: string;
39
+ transcriptPath?: string;
40
+ statusPath?: string;
41
+ eventsPath?: string;
42
+ outputPath?: string;
43
+ toolUses?: number;
44
+ jsonEvents?: number;
45
+ model?: string;
46
+ routing?: ModelRoutingState;
47
+ usage?: UsageState;
48
+ progress?: CrewAgentProgress;
49
+ error?: string;
50
+ }
51
+
52
+ export function taskStatusToAgentStatus(status: TeamTaskStatus): CrewAgentStatus {
53
+ if (status === "completed") return "completed";
54
+ if (status === "failed") return "failed";
55
+ if (status === "cancelled" || status === "skipped") return "cancelled";
56
+ if (status === "running") return "running";
57
+ return "queued";
58
+ }
@@ -1,35 +1,35 @@
1
- import type { AgentConfig } from "../agents/agent-config.ts";
2
- import type { TeamRunManifest, TeamTaskState } from "../state/types.ts";
3
- import type { TeamConfig } from "../teams/team-config.ts";
4
- import type { WorkflowConfig } from "../workflows/workflow-config.ts";
5
-
6
- export function isDirectRun(manifest: Pick<TeamRunManifest, "team" | "workflow">): boolean {
7
- return manifest.workflow === "direct-agent";
8
- }
9
-
10
- export function directTeamAndWorkflowFromRun(manifest: TeamRunManifest, tasks: TeamTaskState[], agents: AgentConfig[]): { team: TeamConfig; workflow: WorkflowConfig } | undefined {
11
- if (!isDirectRun(manifest)) return undefined;
12
- const firstTask = tasks[0];
13
- const agentName = firstTask?.agent ?? (manifest.team.replace(/^direct-/, "") || "executor");
14
- const agent = agents.find((candidate) => candidate.name === agentName);
15
- const role = firstTask?.role ?? "agent";
16
- const stepId = firstTask?.stepId ?? "01_agent";
17
- return {
18
- team: {
19
- name: manifest.team,
20
- description: `Direct subagent run for ${agentName}`,
21
- source: "builtin",
22
- filePath: "<generated>",
23
- roles: [{ name: role, agent: agentName, description: agent?.description }],
24
- defaultWorkflow: "direct-agent",
25
- workspaceMode: manifest.workspaceMode,
26
- },
27
- workflow: {
28
- name: manifest.workflow ?? "direct-agent",
29
- description: `Direct task for ${agentName}`,
30
- source: "builtin",
31
- filePath: "<generated>",
32
- steps: [{ id: stepId, role, task: "{goal}", model: firstTask?.model }],
33
- },
34
- };
35
- }
1
+ import type { AgentConfig } from "../agents/agent-config.ts";
2
+ import type { TeamRunManifest, TeamTaskState } from "../state/types.ts";
3
+ import type { TeamConfig } from "../teams/team-config.ts";
4
+ import type { WorkflowConfig } from "../workflows/workflow-config.ts";
5
+
6
+ export function isDirectRun(manifest: Pick<TeamRunManifest, "team" | "workflow">): boolean {
7
+ return manifest.workflow === "direct-agent";
8
+ }
9
+
10
+ export function directTeamAndWorkflowFromRun(manifest: TeamRunManifest, tasks: TeamTaskState[], agents: AgentConfig[]): { team: TeamConfig; workflow: WorkflowConfig } | undefined {
11
+ if (!isDirectRun(manifest)) return undefined;
12
+ const firstTask = tasks[0];
13
+ const agentName = firstTask?.agent ?? (manifest.team.replace(/^direct-/, "") || "executor");
14
+ const agent = agents.find((candidate) => candidate.name === agentName);
15
+ const role = firstTask?.role ?? "agent";
16
+ const stepId = firstTask?.stepId ?? "01_agent";
17
+ return {
18
+ team: {
19
+ name: manifest.team,
20
+ description: `Direct subagent run for ${agentName}`,
21
+ source: "builtin",
22
+ filePath: "<generated>",
23
+ roles: [{ name: role, agent: agentName, description: agent?.description }],
24
+ defaultWorkflow: "direct-agent",
25
+ workspaceMode: manifest.workspaceMode,
26
+ },
27
+ workflow: {
28
+ name: manifest.workflow ?? "direct-agent",
29
+ description: `Direct task for ${agentName}`,
30
+ source: "builtin",
31
+ filePath: "<generated>",
32
+ steps: [{ id: stepId, role, task: "{goal}", model: firstTask?.model }],
33
+ },
34
+ };
35
+ }