pi-crew 0.1.41 → 0.1.44

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 (191) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +51 -0
  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/refactor-tasks-phase3.md +394 -394
  14. package/docs/refactor-tasks-phase4.md +564 -564
  15. package/docs/refactor-tasks-phase5.md +402 -402
  16. package/docs/refactor-tasks-phase6.md +662 -662
  17. package/docs/research-extension-examples.md +297 -297
  18. package/docs/research-extension-system.md +324 -324
  19. package/docs/research-optimization-plan.md +548 -548
  20. package/docs/research-phase10-distillation.md +199 -0
  21. package/docs/research-phase11-distillation.md +201 -0
  22. package/docs/research-pi-coding-agent.md +357 -357
  23. package/docs/research-source-pi-crew-reference.md +174 -174
  24. package/docs/runtime-flow.md +148 -148
  25. package/docs/source-runtime-refactor-map.md +83 -83
  26. package/index.ts +6 -6
  27. package/package.json +1 -1
  28. package/src/agents/agent-serializer.ts +34 -34
  29. package/src/agents/discover-agents.ts +5 -4
  30. package/src/config/config.ts +28 -4
  31. package/src/extension/cross-extension-rpc.ts +82 -82
  32. package/src/extension/management.ts +37 -8
  33. package/src/extension/notification-router.ts +2 -2
  34. package/src/extension/register.ts +130 -8
  35. package/src/extension/registration/commands.ts +11 -9
  36. package/src/extension/registration/compaction-guard.ts +125 -125
  37. package/src/extension/registration/subagent-tools.ts +28 -19
  38. package/src/extension/registration/team-tool.ts +2 -1
  39. package/src/extension/result-watcher.ts +4 -4
  40. package/src/extension/run-bundle-schema.ts +8 -4
  41. package/src/extension/run-import.ts +4 -0
  42. package/src/extension/run-index.ts +23 -1
  43. package/src/extension/run-maintenance.ts +43 -24
  44. package/src/extension/team-tool/api.ts +2 -2
  45. package/src/extension/team-tool/cancel.ts +76 -4
  46. package/src/extension/team-tool/context.ts +1 -0
  47. package/src/extension/team-tool/doctor.ts +8 -1
  48. package/src/extension/team-tool/handle-settings.ts +188 -0
  49. package/src/extension/team-tool/inspect.ts +41 -41
  50. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  51. package/src/extension/team-tool/plan.ts +19 -19
  52. package/src/extension/team-tool/respond.ts +67 -0
  53. package/src/extension/team-tool/run.ts +6 -4
  54. package/src/extension/team-tool/status.ts +99 -93
  55. package/src/extension/team-tool-types.ts +4 -0
  56. package/src/extension/team-tool.ts +5 -1
  57. package/src/i18n.ts +184 -0
  58. package/src/observability/correlation.ts +2 -2
  59. package/src/observability/event-to-metric.ts +10 -3
  60. package/src/observability/exporters/adapter.ts +7 -1
  61. package/src/observability/exporters/otlp-exporter.ts +14 -2
  62. package/src/observability/exporters/prometheus-exporter.ts +9 -2
  63. package/src/observability/metric-registry.ts +18 -3
  64. package/src/observability/metric-retention.ts +11 -3
  65. package/src/observability/metric-sink.ts +9 -4
  66. package/src/observability/metrics-primitives.ts +4 -3
  67. package/src/prompt/prompt-runtime.ts +72 -68
  68. package/src/runtime/agent-control.ts +63 -63
  69. package/src/runtime/agent-memory.ts +72 -72
  70. package/src/runtime/agent-observability.ts +114 -114
  71. package/src/runtime/async-marker.ts +26 -26
  72. package/src/runtime/attention-events.ts +28 -23
  73. package/src/runtime/background-runner.ts +53 -53
  74. package/src/runtime/child-pi.ts +4 -4
  75. package/src/runtime/completion-guard.ts +95 -4
  76. package/src/runtime/concurrency.ts +1 -1
  77. package/src/runtime/crash-recovery.ts +32 -1
  78. package/src/runtime/crew-agent-runtime.ts +59 -58
  79. package/src/runtime/deadletter.ts +14 -4
  80. package/src/runtime/delivery-coordinator.ts +143 -0
  81. package/src/runtime/direct-run.ts +35 -35
  82. package/src/runtime/foreground-control.ts +82 -82
  83. package/src/runtime/green-contract.ts +46 -46
  84. package/src/runtime/group-join.ts +106 -106
  85. package/src/runtime/heartbeat-gradient.ts +28 -28
  86. package/src/runtime/heartbeat-watcher.ts +48 -4
  87. package/src/runtime/live-agent-control.ts +87 -87
  88. package/src/runtime/live-agent-manager.ts +85 -85
  89. package/src/runtime/live-control-realtime.ts +36 -36
  90. package/src/runtime/live-session-runtime.ts +305 -305
  91. package/src/runtime/manifest-cache.ts +2 -2
  92. package/src/runtime/model-fallback.ts +272 -261
  93. package/src/runtime/overflow-recovery.ts +157 -0
  94. package/src/runtime/parallel-research.ts +44 -44
  95. package/src/runtime/parallel-utils.ts +1 -1
  96. package/src/runtime/pi-json-output.ts +111 -111
  97. package/src/runtime/policy-engine.ts +79 -78
  98. package/src/runtime/post-exit-stdio-guard.ts +2 -2
  99. package/src/runtime/process-status.ts +56 -56
  100. package/src/runtime/progress-event-coalescer.ts +43 -43
  101. package/src/runtime/recovery-recipes.ts +74 -74
  102. package/src/runtime/retry-executor.ts +5 -0
  103. package/src/runtime/role-permission.ts +39 -39
  104. package/src/runtime/runtime-resolver.ts +1 -1
  105. package/src/runtime/session-resources.ts +25 -0
  106. package/src/runtime/session-snapshot.ts +59 -0
  107. package/src/runtime/session-usage.ts +79 -79
  108. package/src/runtime/sidechain-output.ts +29 -29
  109. package/src/runtime/stale-reconciler.ts +179 -0
  110. package/src/runtime/subagent-manager.ts +3 -3
  111. package/src/runtime/supervisor-contact.ts +59 -0
  112. package/src/runtime/task-display.ts +38 -38
  113. package/src/runtime/task-output-context.ts +127 -127
  114. package/src/runtime/task-runner/live-executor.ts +101 -101
  115. package/src/runtime/task-runner/progress.ts +119 -111
  116. package/src/runtime/task-runner/result-utils.ts +14 -14
  117. package/src/runtime/task-runner/state-helpers.ts +22 -22
  118. package/src/runtime/task-runner.ts +14 -0
  119. package/src/runtime/team-runner.ts +9 -10
  120. package/src/runtime/worker-heartbeat.ts +21 -21
  121. package/src/runtime/worker-startup.ts +57 -57
  122. package/src/schema/config-schema.ts +2 -1
  123. package/src/schema/team-tool-schema.ts +115 -109
  124. package/src/state/artifact-store.ts +4 -2
  125. package/src/state/atomic-write.ts +12 -4
  126. package/src/state/contracts.ts +109 -105
  127. package/src/state/event-log.ts +3 -4
  128. package/src/state/jsonl-writer.ts +4 -1
  129. package/src/state/locks.ts +9 -1
  130. package/src/state/task-claims.ts +44 -42
  131. package/src/state/usage.ts +29 -29
  132. package/src/subagents/async-entry.ts +1 -1
  133. package/src/subagents/index.ts +3 -3
  134. package/src/subagents/live/control.ts +1 -1
  135. package/src/subagents/live/manager.ts +1 -1
  136. package/src/subagents/live/realtime.ts +1 -1
  137. package/src/subagents/live/session-runtime.ts +1 -1
  138. package/src/subagents/manager.ts +1 -1
  139. package/src/subagents/spawn.ts +1 -1
  140. package/src/teams/discover-teams.ts +2 -2
  141. package/src/teams/team-serializer.ts +38 -38
  142. package/src/types/diff.d.ts +18 -18
  143. package/src/ui/crew-footer.ts +101 -101
  144. package/src/ui/crew-select-list.ts +111 -111
  145. package/src/ui/crew-widget.ts +5 -4
  146. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  147. package/src/ui/dynamic-border.ts +25 -25
  148. package/src/ui/layout-primitives.ts +106 -106
  149. package/src/ui/live-run-sidebar.ts +1 -1
  150. package/src/ui/loaders.ts +158 -158
  151. package/src/ui/mascot.ts +3 -2
  152. package/src/ui/powerbar-publisher.ts +7 -6
  153. package/src/ui/render-diff.ts +119 -119
  154. package/src/ui/render-scheduler.ts +54 -14
  155. package/src/ui/run-dashboard.ts +39 -11
  156. package/src/ui/run-snapshot-cache.ts +336 -36
  157. package/src/ui/spinner.ts +17 -17
  158. package/src/ui/status-colors.ts +58 -54
  159. package/src/ui/syntax-highlight.ts +116 -116
  160. package/src/ui/theme-adapter.ts +1 -1
  161. package/src/ui/transcript-viewer.ts +7 -2
  162. package/src/utils/atomic-write.ts +33 -0
  163. package/src/utils/completion-dedupe.ts +63 -63
  164. package/src/utils/file-coalescer.ts +5 -3
  165. package/src/utils/frontmatter.ts +68 -36
  166. package/src/utils/git.ts +262 -262
  167. package/src/utils/ids.ts +12 -12
  168. package/src/utils/internal-error.ts +1 -1
  169. package/src/utils/names.ts +27 -26
  170. package/src/utils/paths.ts +1 -1
  171. package/src/utils/redaction.ts +44 -41
  172. package/src/utils/safe-paths.ts +47 -34
  173. package/src/utils/sleep.ts +2 -2
  174. package/src/utils/timings.ts +2 -0
  175. package/src/utils/visual.ts +9 -1
  176. package/src/workflows/discover-workflows.ts +4 -1
  177. package/src/workflows/validate-workflow.ts +40 -40
  178. package/src/worktree/branch-freshness.ts +45 -45
  179. package/src/worktree/worktree-manager.ts +6 -1
  180. package/teams/default.team.md +12 -12
  181. package/teams/fast-fix.team.md +11 -11
  182. package/teams/implementation.team.md +18 -18
  183. package/teams/parallel-research.team.md +14 -14
  184. package/teams/research.team.md +11 -11
  185. package/teams/review.team.md +12 -12
  186. package/workflows/default.workflow.md +29 -29
  187. package/workflows/fast-fix.workflow.md +22 -22
  188. package/workflows/implementation.workflow.md +38 -38
  189. package/workflows/parallel-research.workflow.md +46 -46
  190. package/workflows/research.workflow.md +22 -22
  191. package/workflows/review.workflow.md +30 -30
@@ -1,127 +1,127 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import type { ArtifactDescriptor, TeamRunManifest, TeamTaskState } from "../state/types.ts";
4
- import { writeArtifact } from "../state/artifact-store.ts";
5
- import { resolveRealContainedPath } from "../utils/safe-paths.ts";
6
- import type { WorkflowStep } from "../workflows/workflow-config.ts";
7
-
8
- export interface DependencyOutputContext {
9
- dependencies: Array<{ taskId: string; title: string; status: string; result?: string; resultPath?: string }>;
10
- sharedReads: Array<{ name: string; path: string; content: string }>;
11
- }
12
-
13
- function containedExists(filePath: string, baseDir?: string): boolean {
14
- try {
15
- const safePath = baseDir ? resolveRealContainedPath(baseDir, filePath) : filePath;
16
- return fs.existsSync(safePath);
17
- } catch {
18
- return false;
19
- }
20
- }
21
-
22
- function readIfSmall(filePath: string, maxBytes = 24_000, baseDir?: string): string | undefined {
23
- try {
24
- const safePath = baseDir ? resolveRealContainedPath(baseDir, filePath) : filePath;
25
- const stat = fs.statSync(safePath);
26
- if (stat.size > maxBytes) return `${fs.readFileSync(safePath, "utf-8").slice(0, maxBytes)}\n\n...(truncated ${stat.size - maxBytes} bytes)`;
27
- return fs.readFileSync(safePath, "utf-8");
28
- } catch {
29
- return undefined;
30
- }
31
- }
32
-
33
- function safeSharedName(name: string): string {
34
- const normalized = name.replaceAll("\\", "/").replace(/^\.\/+/, "");
35
- if (!normalized || normalized.split("/").some((segment) => segment === "..") || path.isAbsolute(normalized)) throw new Error(`Invalid shared artifact name: ${name}`);
36
- return normalized;
37
- }
38
-
39
- export function sharedPath(manifest: TeamRunManifest, name: string): string {
40
- const sharedRoot = path.resolve(manifest.artifactsRoot, "shared");
41
- const resolved = path.resolve(sharedRoot, safeSharedName(name));
42
- const relative = path.relative(sharedRoot, resolved);
43
- if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`Invalid shared artifact name: ${name}`);
44
- return resolved;
45
- }
46
-
47
- export function collectDependencyOutputContext(manifest: TeamRunManifest, tasks: TeamTaskState[], task: TeamTaskState, step: WorkflowStep): DependencyOutputContext {
48
- const byStep = new Map(tasks.map((item) => [item.stepId, item]).filter((entry): entry is [string, TeamTaskState] => Boolean(entry[0])));
49
- const byId = new Map(tasks.map((item) => [item.id, item]));
50
- const dependencies = task.dependsOn.map((dep) => byStep.get(dep) ?? byId.get(dep)).filter((item): item is TeamTaskState => Boolean(item)).map((item) => ({
51
- taskId: item.id,
52
- title: item.title,
53
- status: item.status,
54
- resultPath: item.resultArtifact?.path,
55
- result: item.resultArtifact ? readIfSmall(item.resultArtifact.path, 24_000, manifest.artifactsRoot) : undefined,
56
- }));
57
- const sharedReads = (step.reads === false ? [] : step.reads ?? []).map((name) => {
58
- const filePath = sharedPath(manifest, name);
59
- return { name, path: filePath, content: readIfSmall(filePath, 24_000, path.resolve(manifest.artifactsRoot, "shared")) ?? "" };
60
- }).filter((item) => item.content.trim().length > 0);
61
- return { dependencies, sharedReads };
62
- }
63
-
64
- export function renderDependencyOutputContext(context: DependencyOutputContext): string {
65
- const parts: string[] = [];
66
- if (context.dependencies.length) {
67
- parts.push("# Dependency Outputs", "");
68
- for (const dep of context.dependencies) {
69
- parts.push(`## ${dep.taskId} (${dep.title})`, `Status: ${dep.status}`, dep.resultPath ? `Result artifact: ${dep.resultPath}` : "", "", dep.result?.trim() || "(no result output)", "");
70
- }
71
- }
72
- if (context.sharedReads.length) {
73
- parts.push("# Shared Run Context Reads", "");
74
- for (const read of context.sharedReads) parts.push(`## shared/${read.name}`, `Path: ${read.path}`, "", read.content.trim(), "");
75
- }
76
- return parts.join("\n").trim();
77
- }
78
-
79
- export function writeTaskSharedOutput(manifest: TeamRunManifest, step: WorkflowStep, task: TeamTaskState): ArtifactDescriptor | undefined {
80
- if (step.output === false) return undefined;
81
- const name = safeSharedName(step.output || `${task.id}.md`);
82
- const source = task.resultArtifact ? readIfSmall(task.resultArtifact.path, 80_000, manifest.artifactsRoot) : undefined;
83
- if (!source) return undefined;
84
- return writeArtifact(manifest.artifactsRoot, {
85
- kind: "metadata",
86
- relativePath: `shared/${name}`,
87
- producer: task.id,
88
- content: source.endsWith("\n") ? source : `${source}\n`,
89
- });
90
- }
91
-
92
- export function writeTaskInputsArtifact(manifest: TeamRunManifest, task: TeamTaskState, context: DependencyOutputContext): ArtifactDescriptor {
93
- return writeArtifact(manifest.artifactsRoot, {
94
- kind: "metadata",
95
- relativePath: `metadata/${task.id}.inputs.json`,
96
- producer: task.id,
97
- content: `${JSON.stringify(context, null, 2)}\n`,
98
- });
99
- }
100
-
101
- export function aggregateTaskOutputs(tasks: TeamTaskState[], manifest?: TeamRunManifest): string {
102
- return tasks.map((task, index) => {
103
- const body = task.resultArtifact ? readIfSmall(task.resultArtifact.path, 40_000, manifest?.artifactsRoot) : undefined;
104
- const hasBody = Boolean(body?.trim());
105
- const expectedMissing = task.resultArtifact && !containedExists(task.resultArtifact.path, manifest?.artifactsRoot);
106
- const status = task.status === "skipped"
107
- ? "SKIPPED"
108
- : task.status === "failed"
109
- ? `FAILED${task.exitCode !== undefined ? ` (exit code ${task.exitCode ?? "null"})` : ""}${task.error ? `: ${task.error}` : ""}`
110
- : expectedMissing
111
- ? `EMPTY OUTPUT (expected result artifact missing: ${task.resultArtifact?.path})`
112
- : !hasBody
113
- ? "EMPTY OUTPUT (no textual response returned)"
114
- : task.status.toUpperCase();
115
- return [
116
- `=== Task ${index + 1}: ${task.id} (${task.agent}) ===`,
117
- `Status: ${status}`,
118
- task.role ? `Role: ${task.role}` : "",
119
- task.resultArtifact?.path ? `Result artifact: ${task.resultArtifact.path}` : "",
120
- task.logArtifact?.path ? `Log artifact: ${task.logArtifact.path}` : "",
121
- task.transcriptArtifact?.path ? `Transcript: ${task.transcriptArtifact.path}` : "",
122
- task.usage ? `Usage: ${JSON.stringify(task.usage)}` : "",
123
- "",
124
- hasBody ? body!.trim() : status,
125
- ].filter(Boolean).join("\n");
126
- }).join("\n\n");
127
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ArtifactDescriptor, TeamRunManifest, TeamTaskState } from "../state/types.ts";
4
+ import { writeArtifact } from "../state/artifact-store.ts";
5
+ import { resolveRealContainedPath } from "../utils/safe-paths.ts";
6
+ import type { WorkflowStep } from "../workflows/workflow-config.ts";
7
+
8
+ export interface DependencyOutputContext {
9
+ dependencies: Array<{ taskId: string; title: string; status: string; result?: string; resultPath?: string }>;
10
+ sharedReads: Array<{ name: string; path: string; content: string }>;
11
+ }
12
+
13
+ function containedExists(filePath: string, baseDir?: string): boolean {
14
+ try {
15
+ const safePath = baseDir ? resolveRealContainedPath(baseDir, filePath) : filePath;
16
+ return fs.existsSync(safePath);
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
21
+
22
+ function readIfSmall(filePath: string, maxBytes = 24_000, baseDir?: string): string | undefined {
23
+ try {
24
+ const safePath = baseDir ? resolveRealContainedPath(baseDir, filePath) : filePath;
25
+ const stat = fs.statSync(safePath);
26
+ if (stat.size > maxBytes) return `${fs.readFileSync(safePath, "utf-8").slice(0, maxBytes)}\n\n...(truncated ${stat.size - maxBytes} bytes)`;
27
+ return fs.readFileSync(safePath, "utf-8");
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ function safeSharedName(name: string): string {
34
+ const normalized = name.replaceAll("\\", "/").replace(/^\.\/+/, "");
35
+ if (!normalized || normalized.split("/").some((segment) => segment === "..") || path.isAbsolute(normalized)) throw new Error(`Invalid shared artifact name: ${name}`);
36
+ return normalized;
37
+ }
38
+
39
+ export function sharedPath(manifest: TeamRunManifest, name: string): string {
40
+ const sharedRoot = path.resolve(manifest.artifactsRoot, "shared");
41
+ const resolved = path.resolve(sharedRoot, safeSharedName(name));
42
+ const relative = path.relative(sharedRoot, resolved);
43
+ if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`Invalid shared artifact name: ${name}`);
44
+ return resolved;
45
+ }
46
+
47
+ export function collectDependencyOutputContext(manifest: TeamRunManifest, tasks: TeamTaskState[], task: TeamTaskState, step: WorkflowStep): DependencyOutputContext {
48
+ const byStep = new Map(tasks.map((item) => [item.stepId, item]).filter((entry): entry is [string, TeamTaskState] => Boolean(entry[0])));
49
+ const byId = new Map(tasks.map((item) => [item.id, item]));
50
+ const dependencies = task.dependsOn.map((dep) => byStep.get(dep) ?? byId.get(dep)).filter((item): item is TeamTaskState => Boolean(item)).map((item) => ({
51
+ taskId: item.id,
52
+ title: item.title,
53
+ status: item.status,
54
+ resultPath: item.resultArtifact?.path,
55
+ result: item.resultArtifact ? readIfSmall(item.resultArtifact.path, 24_000, manifest.artifactsRoot) : undefined,
56
+ }));
57
+ const sharedReads = (step.reads === false ? [] : step.reads ?? []).map((name) => {
58
+ const filePath = sharedPath(manifest, name);
59
+ return { name, path: filePath, content: readIfSmall(filePath, 24_000, path.resolve(manifest.artifactsRoot, "shared")) ?? "" };
60
+ }).filter((item) => item.content.trim().length > 0);
61
+ return { dependencies, sharedReads };
62
+ }
63
+
64
+ export function renderDependencyOutputContext(context: DependencyOutputContext): string {
65
+ const parts: string[] = [];
66
+ if (context.dependencies.length) {
67
+ parts.push("# Dependency Outputs", "");
68
+ for (const dep of context.dependencies) {
69
+ parts.push(`## ${dep.taskId} (${dep.title})`, `Status: ${dep.status}`, dep.resultPath ? `Result artifact: ${dep.resultPath}` : "", "", dep.result?.trim() || "(no result output)", "");
70
+ }
71
+ }
72
+ if (context.sharedReads.length) {
73
+ parts.push("# Shared Run Context Reads", "");
74
+ for (const read of context.sharedReads) parts.push(`## shared/${read.name}`, `Path: ${read.path}`, "", read.content.trim(), "");
75
+ }
76
+ return parts.join("\n").trim();
77
+ }
78
+
79
+ export function writeTaskSharedOutput(manifest: TeamRunManifest, step: WorkflowStep, task: TeamTaskState): ArtifactDescriptor | undefined {
80
+ if (step.output === false) return undefined;
81
+ const name = safeSharedName(step.output || `${task.id}.md`);
82
+ const source = task.resultArtifact ? readIfSmall(task.resultArtifact.path, 80_000, manifest.artifactsRoot) : undefined;
83
+ if (!source) return undefined;
84
+ return writeArtifact(manifest.artifactsRoot, {
85
+ kind: "metadata",
86
+ relativePath: `shared/${name}`,
87
+ producer: task.id,
88
+ content: source.endsWith("\n") ? source : `${source}\n`,
89
+ });
90
+ }
91
+
92
+ export function writeTaskInputsArtifact(manifest: TeamRunManifest, task: TeamTaskState, context: DependencyOutputContext): ArtifactDescriptor {
93
+ return writeArtifact(manifest.artifactsRoot, {
94
+ kind: "metadata",
95
+ relativePath: `metadata/${task.id}.inputs.json`,
96
+ producer: task.id,
97
+ content: `${JSON.stringify(context, null, 2)}\n`,
98
+ });
99
+ }
100
+
101
+ export function aggregateTaskOutputs(tasks: TeamTaskState[], manifest?: TeamRunManifest): string {
102
+ return tasks.map((task, index) => {
103
+ const body = task.resultArtifact ? readIfSmall(task.resultArtifact.path, 40_000, manifest?.artifactsRoot) : undefined;
104
+ const hasBody = Boolean(body?.trim());
105
+ const expectedMissing = task.resultArtifact && !containedExists(task.resultArtifact.path, manifest?.artifactsRoot);
106
+ const status = task.status === "skipped"
107
+ ? "SKIPPED"
108
+ : task.status === "failed"
109
+ ? `FAILED${task.exitCode !== undefined ? ` (exit code ${task.exitCode ?? "null"})` : ""}${task.error ? `: ${task.error}` : ""}`
110
+ : expectedMissing
111
+ ? `EMPTY OUTPUT (expected result artifact missing: ${task.resultArtifact?.path})`
112
+ : !hasBody
113
+ ? "EMPTY OUTPUT (no textual response returned)"
114
+ : task.status.toUpperCase();
115
+ return [
116
+ `=== Task ${index + 1}: ${task.id} (${task.agent}) ===`,
117
+ `Status: ${status}`,
118
+ task.role ? `Role: ${task.role}` : "",
119
+ task.resultArtifact?.path ? `Result artifact: ${task.resultArtifact.path}` : "",
120
+ task.logArtifact?.path ? `Log artifact: ${task.logArtifact.path}` : "",
121
+ task.transcriptArtifact?.path ? `Transcript: ${task.transcriptArtifact.path}` : "",
122
+ task.usage ? `Usage: ${JSON.stringify(task.usage)}` : "",
123
+ "",
124
+ hasBody ? body!.trim() : status,
125
+ ].filter(Boolean).join("\n");
126
+ }).join("\n\n");
127
+ }
@@ -1,101 +1,101 @@
1
- import * as fs from "node:fs";
2
- import type { AgentConfig } from "../../agents/agent-config.ts";
3
- import type { CrewRuntimeConfig } from "../../config/config.ts";
4
- import { writeArtifact } from "../../state/artifact-store.ts";
5
- import { appendEvent } from "../../state/event-log.ts";
6
- import type { ArtifactDescriptor, TeamRunManifest, TeamTaskState } from "../../state/types.ts";
7
- import type { WorkflowStep } from "../../workflows/workflow-config.ts";
8
- import { appendCrewAgentEvent, appendCrewAgentOutput, emptyCrewAgentProgress, recordFromTask, upsertCrewAgent } from "../crew-agent-records.ts";
9
- import { createStartupEvidence, type WorkerStartupEvidence } from "../worker-startup.ts";
10
- import { runLiveSessionTask } from "../live-session-runtime.ts";
11
- import { shouldAppendProgressEventUpdate, type ProgressEventSummary } from "../progress-event-coalescer.ts";
12
- import { applyAgentProgressEvent, applyUsageToProgress, progressEventSummary, shouldFlushProgressEvent } from "./progress.ts";
13
- import type { ParsedPiJsonOutput } from "../pi-json-output.ts";
14
-
15
- export interface RunLiveTaskInput {
16
- manifest: TeamRunManifest;
17
- tasks: TeamTaskState[];
18
- task: TeamTaskState;
19
- step: WorkflowStep;
20
- agent: AgentConfig;
21
- prompt: string;
22
- signal?: AbortSignal;
23
- runtimeConfig?: CrewRuntimeConfig;
24
- parentContext?: string;
25
- parentModel?: unknown;
26
- modelRegistry?: unknown;
27
- isCurrent?: () => boolean;
28
- }
29
-
30
- export interface RunLiveTaskOutput {
31
- task: TeamTaskState;
32
- tasks: TeamTaskState[];
33
- startupEvidence: WorkerStartupEvidence;
34
- exitCode: number | null;
35
- error?: string;
36
- parsedOutput?: ParsedPiJsonOutput;
37
- resultArtifact: ArtifactDescriptor;
38
- logArtifact?: ArtifactDescriptor;
39
- transcriptArtifact?: ArtifactDescriptor;
40
- }
41
-
42
- function updateTask(tasks: TeamTaskState[], updated: TeamTaskState): TeamTaskState[] {
43
- return tasks.map((task) => task.id === updated.id ? updated : task);
44
- }
45
-
46
- export async function runLiveTask(input: RunLiveTaskInput): Promise<RunLiveTaskOutput> {
47
- const { manifest, step, agent, prompt } = input;
48
- let task = input.task;
49
- let tasks = input.tasks;
50
- const transcriptPath = `${manifest.artifactsRoot}/transcripts/${task.id}.jsonl`;
51
- let lastAgentRecordPersistedAt = 0;
52
- let lastRunProgressPersistedAt = 0;
53
- let lastRunProgressSummary: ProgressEventSummary | undefined;
54
- const persistLiveProgress = (event: unknown, force = false): void => {
55
- const now = Date.now();
56
- if (force || shouldFlushProgressEvent(event) || now - lastAgentRecordPersistedAt >= 500) {
57
- upsertCrewAgent(manifest, recordFromTask(manifest, task, "live-session"));
58
- lastAgentRecordPersistedAt = now;
59
- }
60
- const summary = progressEventSummary(task, event);
61
- const decision = shouldAppendProgressEventUpdate({ previous: lastRunProgressSummary, next: summary, nowMs: now, lastAppendMs: lastRunProgressPersistedAt || undefined, minIntervalMs: 1000, force });
62
- if (decision.shouldAppend) {
63
- appendEvent(manifest.eventsPath, { type: "task.progress", runId: manifest.runId, taskId: task.id, data: { ...summary, coalesceReason: decision.reason } });
64
- lastRunProgressSummary = summary;
65
- lastRunProgressPersistedAt = now;
66
- }
67
- };
68
- const attemptStartedAt = new Date();
69
- const isCurrent = input.isCurrent ?? (() => input.signal?.aborted !== true);
70
- const liveResult = await runLiveSessionTask({
71
- manifest,
72
- task,
73
- step,
74
- agent,
75
- prompt,
76
- signal: input.signal,
77
- transcriptPath,
78
- runtimeConfig: input.runtimeConfig,
79
- parentContext: input.parentContext,
80
- parentModel: input.parentModel,
81
- modelRegistry: input.modelRegistry,
82
- isCurrent,
83
- onOutput: (text) => appendCrewAgentOutput(manifest, task.id, text),
84
- onEvent: (event) => {
85
- appendCrewAgentEvent(manifest, task.id, event);
86
- task = { ...task, agentProgress: applyAgentProgressEvent(task.agentProgress ?? emptyCrewAgentProgress(), event, task.startedAt) };
87
- tasks = updateTask(tasks, task);
88
- persistLiveProgress(event);
89
- },
90
- });
91
- const startupEvidence = createStartupEvidence({ command: "live-session", startedAt: attemptStartedAt, finishedAt: new Date(), promptSentAt: attemptStartedAt, promptAccepted: liveResult.exitCode === 0 && !liveResult.error, stderr: liveResult.stderr, error: liveResult.error, exitCode: liveResult.exitCode });
92
- const exitCode = liveResult.exitCode;
93
- const error = liveResult.error || (liveResult.exitCode && liveResult.exitCode !== 0 ? liveResult.stderr || `Live session exited with ${liveResult.exitCode}` : undefined);
94
- const parsedOutput = { finalText: liveResult.stdout, textEvents: liveResult.stdout ? [liveResult.stdout] : [], jsonEvents: liveResult.jsonEvents, usage: liveResult.usage };
95
- if (liveResult.usage) task = { ...task, usage: liveResult.usage, agentProgress: applyUsageToProgress(task.agentProgress, liveResult.usage) };
96
- persistLiveProgress({ type: "attempt_finished" }, true);
97
- const resultArtifact = writeArtifact(manifest.artifactsRoot, { kind: "result", relativePath: `results/${task.id}.txt`, content: liveResult.stdout || liveResult.stderr || "(no output)", producer: task.id });
98
- const logArtifact = writeArtifact(manifest.artifactsRoot, { kind: "log", relativePath: `logs/${task.id}.log`, content: [`runtime=live-session`, `finalExitCode=${exitCode ?? "null"}`, `jsonEvents=${liveResult.jsonEvents}`, liveResult.usage ? `usage=${JSON.stringify(liveResult.usage)}` : "", "", "STDOUT:", liveResult.stdout, "", "STDERR:", liveResult.stderr].join("\n"), producer: task.id });
99
- const transcriptArtifact = fs.existsSync(transcriptPath) ? writeArtifact(manifest.artifactsRoot, { kind: "log", relativePath: `transcripts/${task.id}.jsonl`, content: fs.readFileSync(transcriptPath, "utf-8"), producer: task.id }) : undefined;
100
- return { task, tasks, startupEvidence, exitCode, error: error || undefined, parsedOutput, resultArtifact, logArtifact, transcriptArtifact };
101
- }
1
+ import * as fs from "node:fs";
2
+ import type { AgentConfig } from "../../agents/agent-config.ts";
3
+ import type { CrewRuntimeConfig } from "../../config/config.ts";
4
+ import { writeArtifact } from "../../state/artifact-store.ts";
5
+ import { appendEvent } from "../../state/event-log.ts";
6
+ import type { ArtifactDescriptor, TeamRunManifest, TeamTaskState } from "../../state/types.ts";
7
+ import type { WorkflowStep } from "../../workflows/workflow-config.ts";
8
+ import { appendCrewAgentEvent, appendCrewAgentOutput, emptyCrewAgentProgress, recordFromTask, upsertCrewAgent } from "../crew-agent-records.ts";
9
+ import { createStartupEvidence, type WorkerStartupEvidence } from "../worker-startup.ts";
10
+ import { runLiveSessionTask } from "../live-session-runtime.ts";
11
+ import { shouldAppendProgressEventUpdate, type ProgressEventSummary } from "../progress-event-coalescer.ts";
12
+ import { applyAgentProgressEvent, applyUsageToProgress, progressEventSummary, shouldFlushProgressEvent } from "./progress.ts";
13
+ import type { ParsedPiJsonOutput } from "../pi-json-output.ts";
14
+
15
+ export interface RunLiveTaskInput {
16
+ manifest: TeamRunManifest;
17
+ tasks: TeamTaskState[];
18
+ task: TeamTaskState;
19
+ step: WorkflowStep;
20
+ agent: AgentConfig;
21
+ prompt: string;
22
+ signal?: AbortSignal;
23
+ runtimeConfig?: CrewRuntimeConfig;
24
+ parentContext?: string;
25
+ parentModel?: unknown;
26
+ modelRegistry?: unknown;
27
+ isCurrent?: () => boolean;
28
+ }
29
+
30
+ export interface RunLiveTaskOutput {
31
+ task: TeamTaskState;
32
+ tasks: TeamTaskState[];
33
+ startupEvidence: WorkerStartupEvidence;
34
+ exitCode: number | null;
35
+ error?: string;
36
+ parsedOutput?: ParsedPiJsonOutput;
37
+ resultArtifact: ArtifactDescriptor;
38
+ logArtifact?: ArtifactDescriptor;
39
+ transcriptArtifact?: ArtifactDescriptor;
40
+ }
41
+
42
+ function updateTask(tasks: TeamTaskState[], updated: TeamTaskState): TeamTaskState[] {
43
+ return tasks.map((task) => task.id === updated.id ? updated : task);
44
+ }
45
+
46
+ export async function runLiveTask(input: RunLiveTaskInput): Promise<RunLiveTaskOutput> {
47
+ const { manifest, step, agent, prompt } = input;
48
+ let task = input.task;
49
+ let tasks = input.tasks;
50
+ const transcriptPath = `${manifest.artifactsRoot}/transcripts/${task.id}.jsonl`;
51
+ let lastAgentRecordPersistedAt = 0;
52
+ let lastRunProgressPersistedAt = 0;
53
+ let lastRunProgressSummary: ProgressEventSummary | undefined;
54
+ const persistLiveProgress = (event: unknown, force = false): void => {
55
+ const now = Date.now();
56
+ if (force || shouldFlushProgressEvent(event) || now - lastAgentRecordPersistedAt >= 500) {
57
+ upsertCrewAgent(manifest, recordFromTask(manifest, task, "live-session"));
58
+ lastAgentRecordPersistedAt = now;
59
+ }
60
+ const summary = progressEventSummary(task, event);
61
+ const decision = shouldAppendProgressEventUpdate({ previous: lastRunProgressSummary, next: summary, nowMs: now, lastAppendMs: lastRunProgressPersistedAt || undefined, minIntervalMs: 1000, force });
62
+ if (decision.shouldAppend) {
63
+ appendEvent(manifest.eventsPath, { type: "task.progress", runId: manifest.runId, taskId: task.id, data: { ...summary, coalesceReason: decision.reason } });
64
+ lastRunProgressSummary = summary;
65
+ lastRunProgressPersistedAt = now;
66
+ }
67
+ };
68
+ const attemptStartedAt = new Date();
69
+ const isCurrent = input.isCurrent ?? (() => input.signal?.aborted !== true);
70
+ const liveResult = await runLiveSessionTask({
71
+ manifest,
72
+ task,
73
+ step,
74
+ agent,
75
+ prompt,
76
+ signal: input.signal,
77
+ transcriptPath,
78
+ runtimeConfig: input.runtimeConfig,
79
+ parentContext: input.parentContext,
80
+ parentModel: input.parentModel,
81
+ modelRegistry: input.modelRegistry,
82
+ isCurrent,
83
+ onOutput: (text) => appendCrewAgentOutput(manifest, task.id, text),
84
+ onEvent: (event) => {
85
+ appendCrewAgentEvent(manifest, task.id, event);
86
+ task = { ...task, agentProgress: applyAgentProgressEvent(task.agentProgress ?? emptyCrewAgentProgress(), event, task.startedAt) };
87
+ tasks = updateTask(tasks, task);
88
+ persistLiveProgress(event);
89
+ },
90
+ });
91
+ const startupEvidence = createStartupEvidence({ command: "live-session", startedAt: attemptStartedAt, finishedAt: new Date(), promptSentAt: attemptStartedAt, promptAccepted: liveResult.exitCode === 0 && !liveResult.error, stderr: liveResult.stderr, error: liveResult.error, exitCode: liveResult.exitCode });
92
+ const exitCode = liveResult.exitCode;
93
+ const error = liveResult.error || (liveResult.exitCode && liveResult.exitCode !== 0 ? liveResult.stderr || `Live session exited with ${liveResult.exitCode}` : undefined);
94
+ const parsedOutput = { finalText: liveResult.stdout, textEvents: liveResult.stdout ? [liveResult.stdout] : [], jsonEvents: liveResult.jsonEvents, usage: liveResult.usage };
95
+ if (liveResult.usage) task = { ...task, usage: liveResult.usage, agentProgress: applyUsageToProgress(task.agentProgress, liveResult.usage) };
96
+ persistLiveProgress({ type: "attempt_finished" }, true);
97
+ const resultArtifact = writeArtifact(manifest.artifactsRoot, { kind: "result", relativePath: `results/${task.id}.txt`, content: liveResult.stdout || liveResult.stderr || "(no output)", producer: task.id });
98
+ const logArtifact = writeArtifact(manifest.artifactsRoot, { kind: "log", relativePath: `logs/${task.id}.log`, content: [`runtime=live-session`, `finalExitCode=${exitCode ?? "null"}`, `jsonEvents=${liveResult.jsonEvents}`, liveResult.usage ? `usage=${JSON.stringify(liveResult.usage)}` : "", "", "STDOUT:", liveResult.stdout, "", "STDERR:", liveResult.stderr].join("\n"), producer: task.id });
99
+ const transcriptArtifact = fs.existsSync(transcriptPath) ? writeArtifact(manifest.artifactsRoot, { kind: "log", relativePath: `transcripts/${task.id}.jsonl`, content: fs.readFileSync(transcriptPath, "utf-8"), producer: task.id }) : undefined;
100
+ return { task, tasks, startupEvidence, exitCode, error: error || undefined, parsedOutput, resultArtifact, logArtifact, transcriptArtifact };
101
+ }