pi-crew 0.1.44 → 0.1.45

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 (142) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/agents/analyst.md +11 -11
  3. package/agents/critic.md +11 -11
  4. package/agents/executor.md +11 -11
  5. package/agents/explorer.md +11 -11
  6. package/agents/planner.md +11 -11
  7. package/agents/reviewer.md +11 -11
  8. package/agents/security-reviewer.md +11 -11
  9. package/agents/test-engineer.md +11 -11
  10. package/agents/verifier.md +11 -11
  11. package/agents/writer.md +11 -11
  12. package/docs/refactor-tasks-phase3.md +394 -394
  13. package/docs/refactor-tasks-phase4.md +564 -564
  14. package/docs/refactor-tasks-phase5.md +402 -402
  15. package/docs/refactor-tasks-phase6.md +662 -662
  16. package/docs/research-extension-examples.md +297 -297
  17. package/docs/research-extension-system.md +324 -324
  18. package/docs/research-optimization-plan.md +548 -548
  19. package/docs/research-phase10-distillation.md +198 -198
  20. package/docs/research-phase11-distillation.md +201 -201
  21. package/docs/research-pi-coding-agent.md +357 -357
  22. package/docs/research-source-pi-crew-reference.md +174 -174
  23. package/docs/runtime-flow.md +148 -148
  24. package/docs/source-runtime-refactor-map.md +83 -83
  25. package/index.ts +6 -6
  26. package/package.json +1 -1
  27. package/src/agents/agent-serializer.ts +34 -34
  28. package/src/extension/cross-extension-rpc.ts +82 -82
  29. package/src/extension/register.ts +8 -1
  30. package/src/extension/registration/commands.ts +18 -2
  31. package/src/extension/registration/compaction-guard.ts +125 -125
  32. package/src/extension/registration/subagent-tools.ts +148 -148
  33. package/src/extension/registration/team-tool.ts +26 -8
  34. package/src/extension/run-bundle-schema.ts +89 -89
  35. package/src/extension/run-maintenance.ts +43 -43
  36. package/src/extension/team-tool/cancel.ts +105 -102
  37. package/src/extension/team-tool/context.ts +1 -0
  38. package/src/extension/team-tool/handle-settings.ts +188 -188
  39. package/src/extension/team-tool/inspect.ts +41 -41
  40. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  41. package/src/extension/team-tool/plan.ts +19 -19
  42. package/src/extension/team-tool/respond.ts +83 -66
  43. package/src/extension/team-tool/run.ts +1 -0
  44. package/src/i18n.ts +184 -184
  45. package/src/observability/exporters/otlp-exporter.ts +77 -77
  46. package/src/prompt/prompt-runtime.ts +72 -72
  47. package/src/runtime/agent-control.ts +63 -63
  48. package/src/runtime/agent-memory.ts +72 -72
  49. package/src/runtime/agent-observability.ts +114 -114
  50. package/src/runtime/async-marker.ts +26 -26
  51. package/src/runtime/attention-events.ts +28 -28
  52. package/src/runtime/background-runner.ts +53 -53
  53. package/src/runtime/child-pi.ts +444 -444
  54. package/src/runtime/completion-guard.ts +190 -190
  55. package/src/runtime/crew-agent-records.ts +8 -0
  56. package/src/runtime/delivery-coordinator.ts +153 -142
  57. package/src/runtime/direct-run.ts +35 -35
  58. package/src/runtime/foreground-control.ts +82 -82
  59. package/src/runtime/green-contract.ts +46 -46
  60. package/src/runtime/group-join.ts +106 -106
  61. package/src/runtime/heartbeat-gradient.ts +28 -28
  62. package/src/runtime/heartbeat-watcher.ts +124 -124
  63. package/src/runtime/live-agent-control.ts +87 -87
  64. package/src/runtime/live-agent-manager.ts +85 -85
  65. package/src/runtime/live-control-realtime.ts +36 -36
  66. package/src/runtime/live-session-runtime.ts +305 -305
  67. package/src/runtime/overflow-recovery.ts +175 -156
  68. package/src/runtime/parallel-research.ts +44 -44
  69. package/src/runtime/pi-json-output.ts +111 -111
  70. package/src/runtime/policy-engine.ts +79 -79
  71. package/src/runtime/progress-event-coalescer.ts +43 -43
  72. package/src/runtime/recovery-recipes.ts +74 -74
  73. package/src/runtime/retry-executor.ts +64 -64
  74. package/src/runtime/role-permission.ts +39 -39
  75. package/src/runtime/session-resources.ts +25 -25
  76. package/src/runtime/session-snapshot.ts +59 -59
  77. package/src/runtime/session-usage.ts +79 -79
  78. package/src/runtime/sidechain-output.ts +29 -29
  79. package/src/runtime/stale-reconciler.ts +199 -179
  80. package/src/runtime/supervisor-contact.ts +59 -59
  81. package/src/runtime/task-display.ts +38 -38
  82. package/src/runtime/task-output-context.ts +127 -127
  83. package/src/runtime/task-runner/live-executor.ts +101 -101
  84. package/src/runtime/task-runner/progress.ts +119 -119
  85. package/src/runtime/task-runner/result-utils.ts +14 -14
  86. package/src/runtime/task-runner/state-helpers.ts +22 -22
  87. package/src/runtime/team-runner.ts +13 -4
  88. package/src/runtime/worker-heartbeat.ts +21 -21
  89. package/src/runtime/worker-startup.ts +57 -57
  90. package/src/state/state-store.ts +43 -0
  91. package/src/state/task-claims.ts +44 -44
  92. package/src/state/types.ts +2 -0
  93. package/src/state/usage.ts +29 -29
  94. package/src/subagents/async-entry.ts +1 -1
  95. package/src/subagents/index.ts +3 -3
  96. package/src/subagents/live/control.ts +1 -1
  97. package/src/subagents/live/manager.ts +1 -1
  98. package/src/subagents/live/realtime.ts +1 -1
  99. package/src/subagents/live/session-runtime.ts +1 -1
  100. package/src/subagents/manager.ts +1 -1
  101. package/src/subagents/spawn.ts +1 -1
  102. package/src/teams/team-serializer.ts +38 -38
  103. package/src/types/diff.d.ts +18 -18
  104. package/src/ui/crew-footer.ts +101 -101
  105. package/src/ui/crew-select-list.ts +111 -111
  106. package/src/ui/crew-widget.ts +5 -1
  107. package/src/ui/dashboard-panes/mailbox-pane.ts +2 -1
  108. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  109. package/src/ui/dynamic-border.ts +25 -25
  110. package/src/ui/layout-primitives.ts +106 -106
  111. package/src/ui/loaders.ts +158 -158
  112. package/src/ui/powerbar-publisher.ts +1 -1
  113. package/src/ui/render-diff.ts +119 -119
  114. package/src/ui/render-scheduler.ts +143 -143
  115. package/src/ui/run-snapshot-cache.ts +56 -37
  116. package/src/ui/snapshot-types.ts +5 -0
  117. package/src/ui/spinner.ts +17 -17
  118. package/src/ui/status-colors.ts +58 -58
  119. package/src/ui/syntax-highlight.ts +116 -116
  120. package/src/utils/atomic-write.ts +33 -33
  121. package/src/utils/completion-dedupe.ts +63 -63
  122. package/src/utils/frontmatter.ts +68 -68
  123. package/src/utils/git.ts +262 -262
  124. package/src/utils/ids.ts +12 -12
  125. package/src/utils/names.ts +27 -27
  126. package/src/utils/redaction.ts +44 -44
  127. package/src/utils/safe-paths.ts +47 -47
  128. package/src/utils/sleep.ts +32 -32
  129. package/src/workflows/validate-workflow.ts +40 -40
  130. package/src/worktree/branch-freshness.ts +45 -45
  131. package/teams/default.team.md +12 -12
  132. package/teams/fast-fix.team.md +11 -11
  133. package/teams/implementation.team.md +18 -18
  134. package/teams/parallel-research.team.md +14 -14
  135. package/teams/research.team.md +11 -11
  136. package/teams/review.team.md +12 -12
  137. package/workflows/default.workflow.md +29 -29
  138. package/workflows/fast-fix.workflow.md +22 -22
  139. package/workflows/implementation.workflow.md +38 -38
  140. package/workflows/parallel-research.workflow.md +46 -46
  141. package/workflows/research.workflow.md +22 -22
  142. package/workflows/review.workflow.md +30 -30
@@ -1,157 +1,176 @@
1
- import { logInternalError } from "../utils/internal-error.ts";
2
-
3
- export type OverflowPhase = "none" | "compaction" | "retrying" | "recovered" | "failed";
4
-
5
- export interface OverflowRecoveryState {
6
- taskId: string;
7
- runId: string;
8
- phase: OverflowPhase;
9
- startedAt: number;
10
- lastEventAt: number;
11
- compactionCount: number;
12
- retryCount: number;
13
- }
14
-
15
- export interface OverflowRecoveryCallbacks {
16
- onPhaseChange?: (state: OverflowRecoveryState, previousPhase: OverflowPhase) => void;
17
- onTimeout?: (state: OverflowRecoveryState) => void;
18
- }
19
-
20
- const PHASE_TIMEOUT_MS = 120_000; // 120 seconds per phase
21
-
22
- export class OverflowRecoveryTracker {
23
- private states = new Map<string, OverflowRecoveryState>();
24
- private timers = new Map<string, ReturnType<typeof setTimeout>>();
25
- private callbacks: OverflowRecoveryCallbacks;
26
-
27
- constructor(callbacks: OverflowRecoveryCallbacks = {}) {
28
- this.callbacks = callbacks;
29
- }
30
-
31
- feedEvent(taskId: string, runId: string, eventType: string): OverflowPhase {
32
- const existing = this.states.get(taskId);
33
- const now = Date.now();
34
-
35
- if (existing && existing.phase === "recovered") {
36
- existing.lastEventAt = now;
37
- return "recovered";
38
- }
39
- if (existing && existing.phase === "failed") {
40
- existing.lastEventAt = now;
41
- return "failed";
42
- }
43
-
44
- let phase: OverflowPhase = existing?.phase ?? "none";
45
- let compactionCount = existing?.compactionCount ?? 0;
46
- let retryCount = existing?.retryCount ?? 0;
47
- const previousPhase = phase;
48
-
49
- switch (eventType) {
50
- case "compaction_start":
51
- phase = "compaction";
52
- compactionCount++;
53
- break;
54
- case "compaction_end":
55
- // After compaction, we expect a retry; stay in compaction until retry starts
56
- break;
57
- case "auto_retry_start":
58
- phase = "retrying";
59
- retryCount++;
60
- break;
61
- case "auto_retry_end":
62
- // After retry completes, the agent should produce a response
63
- // We consider this recovered but don't finalize until agent_end
64
- phase = "recovered";
65
- break;
66
- case "agent_end":
67
- // If we were recovering and agent ends, we're recovered or failed
68
- if (phase === "compaction" || phase === "retrying") {
69
- phase = "failed";
70
- }
71
- break;
72
- default:
73
- // Unknown event type — no phase change
74
- break;
75
- }
76
-
77
- const state: OverflowRecoveryState = {
78
- taskId,
79
- runId,
80
- phase,
81
- startedAt: existing?.startedAt ?? now,
82
- lastEventAt: now,
83
- compactionCount,
84
- retryCount,
85
- };
86
-
87
- this.states.set(taskId, state);
88
- this.resetTimeout(taskId);
89
-
90
- if (previousPhase !== phase && this.callbacks.onPhaseChange) {
91
- try {
92
- this.callbacks.onPhaseChange(state, previousPhase);
93
- } catch (error) {
94
- logInternalError("overflow-recovery.onPhaseChange", error, `taskId=${taskId}`);
95
- }
96
- }
97
-
98
- return phase;
99
- }
100
-
101
- getState(taskId: string): OverflowRecoveryState | undefined {
102
- return this.states.get(taskId);
103
- }
104
-
105
- getPhase(taskId: string): OverflowPhase {
106
- return this.states.get(taskId)?.phase ?? "none";
107
- }
108
-
109
- removeTask(taskId: string): void {
110
- this.states.delete(taskId);
111
- const timer = this.timers.get(taskId);
112
- if (timer) {
113
- clearTimeout(timer);
114
- this.timers.delete(taskId);
115
- }
116
- }
117
-
118
- dispose(): void {
119
- for (const timer of this.timers.values()) clearTimeout(timer);
120
- this.timers.clear();
121
- this.states.clear();
122
- }
123
-
124
- private resetTimeout(taskId: string): void {
125
- const existing = this.timers.get(taskId);
126
- if (existing) clearTimeout(existing);
127
-
128
- const timer = setTimeout(() => {
129
- this.timers.delete(taskId);
130
- const state = this.states.get(taskId);
131
- if (!state) return;
132
- if (state.phase === "recovered" || state.phase === "failed" || state.phase === "none") return;
133
-
134
- const previousPhase = state.phase;
135
- state.phase = "failed";
136
- state.lastEventAt = Date.now();
137
-
138
- if (this.callbacks.onTimeout) {
139
- try {
140
- this.callbacks.onTimeout(state);
141
- } catch (error) {
142
- logInternalError("overflow-recovery.onTimeout", error, `taskId=${taskId}`);
143
- }
144
- }
145
- if (this.callbacks.onPhaseChange) {
146
- try {
147
- this.callbacks.onPhaseChange(state, previousPhase);
148
- } catch (error) {
149
- logInternalError("overflow-recovery.onPhaseChange-timeout", error, `taskId=${taskId}`);
150
- }
151
- }
152
- }, PHASE_TIMEOUT_MS);
153
-
154
- timer.unref();
155
- this.timers.set(taskId, timer);
156
- }
1
+ import { logInternalError } from "../utils/internal-error.ts";
2
+
3
+ export type OverflowPhase = "none" | "compaction" | "retrying" | "recovered" | "failed";
4
+
5
+ export interface OverflowRecoveryState {
6
+ taskId: string;
7
+ runId: string;
8
+ phase: OverflowPhase;
9
+ startedAt: number;
10
+ lastEventAt: number;
11
+ compactionCount: number;
12
+ retryCount: number;
13
+ }
14
+
15
+ export interface OverflowRecoveryCallbacks {
16
+ onPhaseChange?: (state: OverflowRecoveryState, previousPhase: OverflowPhase) => void;
17
+ onTimeout?: (state: OverflowRecoveryState) => void;
18
+ }
19
+
20
+ const PHASE_TIMEOUT_MS = 120_000; // 120 seconds per phase
21
+ const TERMINAL_STATE_TTL_MS = 5 * 60_000;
22
+
23
+ export class OverflowRecoveryTracker {
24
+ private states = new Map<string, OverflowRecoveryState>();
25
+ private timers = new Map<string, ReturnType<typeof setTimeout>>();
26
+ private callbacks: OverflowRecoveryCallbacks;
27
+
28
+ constructor(callbacks: OverflowRecoveryCallbacks = {}) {
29
+ this.callbacks = callbacks;
30
+ }
31
+
32
+ feedEvent(taskId: string, runId: string, eventType: string): OverflowPhase {
33
+ const key = this.keyFor(taskId, runId);
34
+ const existing = this.states.get(key);
35
+ const now = Date.now();
36
+
37
+ if (existing && existing.phase === "recovered") {
38
+ existing.lastEventAt = now;
39
+ return "recovered";
40
+ }
41
+ if (existing && existing.phase === "failed") {
42
+ existing.lastEventAt = now;
43
+ return "failed";
44
+ }
45
+
46
+ let phase: OverflowPhase = existing?.phase ?? "none";
47
+ let compactionCount = existing?.compactionCount ?? 0;
48
+ let retryCount = existing?.retryCount ?? 0;
49
+ const previousPhase = phase;
50
+
51
+ switch (eventType) {
52
+ case "compaction_start":
53
+ phase = "compaction";
54
+ compactionCount++;
55
+ break;
56
+ case "compaction_end":
57
+ // After compaction, we expect a retry; stay in compaction until retry starts
58
+ break;
59
+ case "auto_retry_start":
60
+ phase = "retrying";
61
+ retryCount++;
62
+ break;
63
+ case "auto_retry_end":
64
+ // After retry completes, the agent should produce a response
65
+ // We consider this recovered but don't finalize until agent_end
66
+ phase = "recovered";
67
+ break;
68
+ case "agent_end":
69
+ // If we were recovering and agent ends, we're recovered or failed
70
+ if (phase === "compaction" || phase === "retrying") {
71
+ phase = "failed";
72
+ }
73
+ break;
74
+ default:
75
+ // Unknown event type — no phase change
76
+ break;
77
+ }
78
+
79
+ const state: OverflowRecoveryState = {
80
+ taskId,
81
+ runId,
82
+ phase,
83
+ startedAt: existing?.startedAt ?? now,
84
+ lastEventAt: now,
85
+ compactionCount,
86
+ retryCount,
87
+ };
88
+
89
+ this.states.set(key, state);
90
+ this.resetTimeout(key);
91
+
92
+ if (previousPhase !== phase && this.callbacks.onPhaseChange) {
93
+ try {
94
+ this.callbacks.onPhaseChange(state, previousPhase);
95
+ } catch (error) {
96
+ logInternalError("overflow-recovery.onPhaseChange", error, `taskId=${taskId}`);
97
+ }
98
+ }
99
+
100
+ return phase;
101
+ }
102
+
103
+ getState(taskId: string, runId?: string): OverflowRecoveryState | undefined {
104
+ if (runId) return this.states.get(this.keyFor(taskId, runId));
105
+ return [...this.states.values()].find((state) => state.taskId === taskId);
106
+ }
107
+
108
+ getPhase(taskId: string, runId?: string): OverflowPhase {
109
+ return this.getState(taskId, runId)?.phase ?? "none";
110
+ }
111
+
112
+ removeTask(taskId: string, runId?: string): void {
113
+ const keys = runId
114
+ ? [this.keyFor(taskId, runId)]
115
+ : [...this.states.entries()].filter(([, state]) => state.taskId === taskId).map(([key]) => key);
116
+ for (const key of keys) this.removeKey(key);
117
+ }
118
+
119
+ dispose(): void {
120
+ for (const timer of this.timers.values()) clearTimeout(timer);
121
+ this.timers.clear();
122
+ this.states.clear();
123
+ }
124
+
125
+ private keyFor(taskId: string, runId: string): string {
126
+ return `${runId}\u0000${taskId}`;
127
+ }
128
+
129
+ private removeKey(key: string): void {
130
+ this.states.delete(key);
131
+ const timer = this.timers.get(key);
132
+ if (timer) clearTimeout(timer);
133
+ this.timers.delete(key);
134
+ }
135
+
136
+ private resetTimeout(key: string): void {
137
+ const existing = this.timers.get(key);
138
+ if (existing) clearTimeout(existing);
139
+ const current = this.states.get(key);
140
+ const timeoutMs = current?.phase === "recovered" || current?.phase === "failed" || current?.phase === "none"
141
+ ? TERMINAL_STATE_TTL_MS
142
+ : PHASE_TIMEOUT_MS;
143
+
144
+ const timer = setTimeout(() => {
145
+ this.timers.delete(key);
146
+ const state = this.states.get(key);
147
+ if (!state) return;
148
+ if (state.phase === "recovered" || state.phase === "failed" || state.phase === "none") {
149
+ this.states.delete(key);
150
+ return;
151
+ }
152
+
153
+ const previousPhase = state.phase;
154
+ state.phase = "failed";
155
+ state.lastEventAt = Date.now();
156
+
157
+ if (this.callbacks.onTimeout) {
158
+ try {
159
+ this.callbacks.onTimeout(state);
160
+ } catch (error) {
161
+ logInternalError("overflow-recovery.onTimeout", error, `taskId=${state.taskId}`);
162
+ }
163
+ }
164
+ if (this.callbacks.onPhaseChange) {
165
+ try {
166
+ this.callbacks.onPhaseChange(state, previousPhase);
167
+ } catch (error) {
168
+ logInternalError("overflow-recovery.onPhaseChange-timeout", error, `taskId=${state.taskId}`);
169
+ }
170
+ }
171
+ }, timeoutMs);
172
+
173
+ timer.unref();
174
+ this.timers.set(key, timer);
175
+ }
157
176
  }
@@ -1,44 +1,44 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import type { WorkflowConfig, WorkflowStep } from "../workflows/workflow-config.ts";
4
-
5
- export function sourcePiProjects(cwd: string): string[] {
6
- const sourceDir = path.join(cwd, "Source");
7
- try {
8
- return fs.readdirSync(sourceDir, { withFileTypes: true })
9
- .filter((entry) => entry.isDirectory() && entry.name.startsWith("pi-"))
10
- .map((entry) => `Source/${entry.name}`)
11
- .sort();
12
- } catch {
13
- return [];
14
- }
15
- }
16
-
17
- export function chunkProjects(projects: string[], target = 6): string[][] {
18
- const chunks = Array.from({ length: Math.min(Math.max(1, target), Math.max(1, projects.length)) }, () => [] as string[]);
19
- projects.forEach((project, index) => chunks[index % chunks.length]!.push(project));
20
- return chunks.filter((chunk) => chunk.length > 0);
21
- }
22
-
23
- export function expandParallelResearchWorkflow(workflow: WorkflowConfig, cwd: string): WorkflowConfig {
24
- if (workflow.name !== "parallel-research") return workflow;
25
- const projects = sourcePiProjects(cwd);
26
- if (projects.length === 0) return workflow;
27
- const chunks = chunkProjects(projects, Math.min(8, Math.max(4, Math.ceil(projects.length / 3))));
28
- const exploreSteps: WorkflowStep[] = chunks.map((paths, index) => ({
29
- id: `explore-shard-${index + 1}`,
30
- role: "explorer",
31
- parallelGroup: "explore",
32
- reads: paths,
33
- task: [`Explore this dynamic shard for: {goal}`, "", "Paths:", ...paths.map((item) => `- ${item}`), "", "Focus on purpose, architecture, runtime/UI patterns, package config, docs, and lessons for pi-crew."].join("\n"),
34
- }));
35
- return {
36
- ...workflow,
37
- steps: [
38
- { id: "discover", role: "explorer", parallelGroup: "inventory", task: `Quickly inventory and validate ${projects.length} pi-* projects for: {goal}\n\nProjects:\n${projects.map((item) => `- ${item}`).join("\n")}\n\nDo not block shard work; summarize routing notes only.` },
39
- ...exploreSteps,
40
- { id: "synthesize", role: "analyst", dependsOn: exploreSteps.map((step) => step.id), task: "Synthesize all dynamic shard findings. Identify common patterns, gaps, and concrete recommendations. Use discover output if available, but prioritize completed shard outputs." },
41
- { id: "write", role: "writer", dependsOn: ["synthesize"], output: "research-summary.md", task: "Write a concise final summary with evidence, risks, and actionable next steps." },
42
- ],
43
- };
44
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { WorkflowConfig, WorkflowStep } from "../workflows/workflow-config.ts";
4
+
5
+ export function sourcePiProjects(cwd: string): string[] {
6
+ const sourceDir = path.join(cwd, "Source");
7
+ try {
8
+ return fs.readdirSync(sourceDir, { withFileTypes: true })
9
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith("pi-"))
10
+ .map((entry) => `Source/${entry.name}`)
11
+ .sort();
12
+ } catch {
13
+ return [];
14
+ }
15
+ }
16
+
17
+ export function chunkProjects(projects: string[], target = 6): string[][] {
18
+ const chunks = Array.from({ length: Math.min(Math.max(1, target), Math.max(1, projects.length)) }, () => [] as string[]);
19
+ projects.forEach((project, index) => chunks[index % chunks.length]!.push(project));
20
+ return chunks.filter((chunk) => chunk.length > 0);
21
+ }
22
+
23
+ export function expandParallelResearchWorkflow(workflow: WorkflowConfig, cwd: string): WorkflowConfig {
24
+ if (workflow.name !== "parallel-research") return workflow;
25
+ const projects = sourcePiProjects(cwd);
26
+ if (projects.length === 0) return workflow;
27
+ const chunks = chunkProjects(projects, Math.min(8, Math.max(4, Math.ceil(projects.length / 3))));
28
+ const exploreSteps: WorkflowStep[] = chunks.map((paths, index) => ({
29
+ id: `explore-shard-${index + 1}`,
30
+ role: "explorer",
31
+ parallelGroup: "explore",
32
+ reads: paths,
33
+ task: [`Explore this dynamic shard for: {goal}`, "", "Paths:", ...paths.map((item) => `- ${item}`), "", "Focus on purpose, architecture, runtime/UI patterns, package config, docs, and lessons for pi-crew."].join("\n"),
34
+ }));
35
+ return {
36
+ ...workflow,
37
+ steps: [
38
+ { id: "discover", role: "explorer", parallelGroup: "inventory", task: `Quickly inventory and validate ${projects.length} pi-* projects for: {goal}\n\nProjects:\n${projects.map((item) => `- ${item}`).join("\n")}\n\nDo not block shard work; summarize routing notes only.` },
39
+ ...exploreSteps,
40
+ { id: "synthesize", role: "analyst", dependsOn: exploreSteps.map((step) => step.id), task: "Synthesize all dynamic shard findings. Identify common patterns, gaps, and concrete recommendations. Use discover output if available, but prioritize completed shard outputs." },
41
+ { id: "write", role: "writer", dependsOn: ["synthesize"], output: "research-summary.md", task: "Write a concise final summary with evidence, risks, and actionable next steps." },
42
+ ],
43
+ };
44
+ }
@@ -1,111 +1,111 @@
1
- export interface ParsedPiUsage {
2
- input?: number;
3
- output?: number;
4
- cacheRead?: number;
5
- cacheWrite?: number;
6
- cost?: number;
7
- turns?: number;
8
- }
9
-
10
- export interface ParsedPiJsonOutput {
11
- jsonEvents: number;
12
- textEvents: string[];
13
- finalText?: string;
14
- usage?: ParsedPiUsage;
15
- }
16
-
17
- function asRecord(value: unknown): Record<string, unknown> | undefined {
18
- return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
19
- }
20
-
21
- function numberField(obj: Record<string, unknown>, keys: string[]): number | undefined {
22
- for (const key of keys) {
23
- const value = obj[key];
24
- if (typeof value === "number" && Number.isFinite(value)) return value;
25
- }
26
- return undefined;
27
- }
28
-
29
- function mergeUsage(target: ParsedPiUsage, source: ParsedPiUsage): ParsedPiUsage {
30
- return {
31
- input: source.input ?? target.input,
32
- output: source.output ?? target.output,
33
- cacheRead: source.cacheRead ?? target.cacheRead,
34
- cacheWrite: source.cacheWrite ?? target.cacheWrite,
35
- cost: source.cost ?? target.cost,
36
- turns: source.turns ?? target.turns,
37
- };
38
- }
39
-
40
- function extractUsage(value: unknown): ParsedPiUsage | undefined {
41
- const obj = asRecord(value);
42
- if (!obj) return undefined;
43
- const direct: ParsedPiUsage = {
44
- input: numberField(obj, ["input", "inputTokens", "input_tokens"]),
45
- output: numberField(obj, ["output", "outputTokens", "output_tokens"]),
46
- cacheRead: numberField(obj, ["cacheRead", "cache_read", "cacheReadTokens", "cache_read_tokens"]),
47
- cacheWrite: numberField(obj, ["cacheWrite", "cache_write", "cacheWriteTokens", "cache_write_tokens"]),
48
- cost: numberField(obj, ["cost", "costUsd", "cost_usd"]),
49
- turns: numberField(obj, ["turns", "turnCount", "turn_count"]),
50
- };
51
- if (Object.values(direct).some((entry) => entry !== undefined)) return direct;
52
- for (const key of ["usage", "tokenUsage", "tokens", "stats"]) {
53
- const nested = extractUsage(obj[key]);
54
- if (nested) return nested;
55
- }
56
- return undefined;
57
- }
58
-
59
- function textFromContent(content: unknown): string[] {
60
- if (typeof content === "string") return [content];
61
- if (!Array.isArray(content)) return [];
62
- const text: string[] = [];
63
- for (const part of content) {
64
- const obj = asRecord(part);
65
- if (!obj) continue;
66
- if (obj.type === "text" && typeof obj.text === "string") text.push(obj.text);
67
- else if (typeof obj.content === "string") text.push(obj.content);
68
- }
69
- return text;
70
- }
71
-
72
- function extractText(value: unknown): string[] {
73
- const obj = asRecord(value);
74
- if (!obj) return [];
75
- const message = asRecord(obj.message);
76
- if (message?.role !== undefined && message.role !== "assistant") return [];
77
- const text: string[] = [];
78
- if (typeof obj.text === "string") text.push(obj.text);
79
- if (typeof obj.output === "string") text.push(obj.output);
80
- if (typeof obj.finalOutput === "string") text.push(obj.finalOutput);
81
- if (typeof obj.final_output === "string") text.push(obj.final_output);
82
- if (!message) text.push(...textFromContent(obj.content));
83
- if (message) text.push(...textFromContent(message.content));
84
- return text.filter((entry) => entry.trim().length > 0);
85
- }
86
-
87
- export function parsePiJsonOutput(stdout: string): ParsedPiJsonOutput {
88
- let jsonEvents = 0;
89
- const textEvents: string[] = [];
90
- let usage: ParsedPiUsage | undefined;
91
- for (const line of stdout.split("\n")) {
92
- const trimmed = line.trim();
93
- if (!trimmed) continue;
94
- let event: unknown;
95
- try {
96
- event = JSON.parse(trimmed) as unknown;
97
- } catch {
98
- continue;
99
- }
100
- jsonEvents++;
101
- textEvents.push(...extractText(event));
102
- const eventUsage = extractUsage(event);
103
- if (eventUsage) usage = mergeUsage(usage ?? {}, eventUsage);
104
- }
105
- return {
106
- jsonEvents,
107
- textEvents,
108
- finalText: textEvents.length > 0 ? textEvents[textEvents.length - 1] : undefined,
109
- usage,
110
- };
111
- }
1
+ export interface ParsedPiUsage {
2
+ input?: number;
3
+ output?: number;
4
+ cacheRead?: number;
5
+ cacheWrite?: number;
6
+ cost?: number;
7
+ turns?: number;
8
+ }
9
+
10
+ export interface ParsedPiJsonOutput {
11
+ jsonEvents: number;
12
+ textEvents: string[];
13
+ finalText?: string;
14
+ usage?: ParsedPiUsage;
15
+ }
16
+
17
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
18
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
19
+ }
20
+
21
+ function numberField(obj: Record<string, unknown>, keys: string[]): number | undefined {
22
+ for (const key of keys) {
23
+ const value = obj[key];
24
+ if (typeof value === "number" && Number.isFinite(value)) return value;
25
+ }
26
+ return undefined;
27
+ }
28
+
29
+ function mergeUsage(target: ParsedPiUsage, source: ParsedPiUsage): ParsedPiUsage {
30
+ return {
31
+ input: source.input ?? target.input,
32
+ output: source.output ?? target.output,
33
+ cacheRead: source.cacheRead ?? target.cacheRead,
34
+ cacheWrite: source.cacheWrite ?? target.cacheWrite,
35
+ cost: source.cost ?? target.cost,
36
+ turns: source.turns ?? target.turns,
37
+ };
38
+ }
39
+
40
+ function extractUsage(value: unknown): ParsedPiUsage | undefined {
41
+ const obj = asRecord(value);
42
+ if (!obj) return undefined;
43
+ const direct: ParsedPiUsage = {
44
+ input: numberField(obj, ["input", "inputTokens", "input_tokens"]),
45
+ output: numberField(obj, ["output", "outputTokens", "output_tokens"]),
46
+ cacheRead: numberField(obj, ["cacheRead", "cache_read", "cacheReadTokens", "cache_read_tokens"]),
47
+ cacheWrite: numberField(obj, ["cacheWrite", "cache_write", "cacheWriteTokens", "cache_write_tokens"]),
48
+ cost: numberField(obj, ["cost", "costUsd", "cost_usd"]),
49
+ turns: numberField(obj, ["turns", "turnCount", "turn_count"]),
50
+ };
51
+ if (Object.values(direct).some((entry) => entry !== undefined)) return direct;
52
+ for (const key of ["usage", "tokenUsage", "tokens", "stats"]) {
53
+ const nested = extractUsage(obj[key]);
54
+ if (nested) return nested;
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ function textFromContent(content: unknown): string[] {
60
+ if (typeof content === "string") return [content];
61
+ if (!Array.isArray(content)) return [];
62
+ const text: string[] = [];
63
+ for (const part of content) {
64
+ const obj = asRecord(part);
65
+ if (!obj) continue;
66
+ if (obj.type === "text" && typeof obj.text === "string") text.push(obj.text);
67
+ else if (typeof obj.content === "string") text.push(obj.content);
68
+ }
69
+ return text;
70
+ }
71
+
72
+ function extractText(value: unknown): string[] {
73
+ const obj = asRecord(value);
74
+ if (!obj) return [];
75
+ const message = asRecord(obj.message);
76
+ if (message?.role !== undefined && message.role !== "assistant") return [];
77
+ const text: string[] = [];
78
+ if (typeof obj.text === "string") text.push(obj.text);
79
+ if (typeof obj.output === "string") text.push(obj.output);
80
+ if (typeof obj.finalOutput === "string") text.push(obj.finalOutput);
81
+ if (typeof obj.final_output === "string") text.push(obj.final_output);
82
+ if (!message) text.push(...textFromContent(obj.content));
83
+ if (message) text.push(...textFromContent(message.content));
84
+ return text.filter((entry) => entry.trim().length > 0);
85
+ }
86
+
87
+ export function parsePiJsonOutput(stdout: string): ParsedPiJsonOutput {
88
+ let jsonEvents = 0;
89
+ const textEvents: string[] = [];
90
+ let usage: ParsedPiUsage | undefined;
91
+ for (const line of stdout.split("\n")) {
92
+ const trimmed = line.trim();
93
+ if (!trimmed) continue;
94
+ let event: unknown;
95
+ try {
96
+ event = JSON.parse(trimmed) as unknown;
97
+ } catch {
98
+ continue;
99
+ }
100
+ jsonEvents++;
101
+ textEvents.push(...extractText(event));
102
+ const eventUsage = extractUsage(event);
103
+ if (eventUsage) usage = mergeUsage(usage ?? {}, eventUsage);
104
+ }
105
+ return {
106
+ jsonEvents,
107
+ textEvents,
108
+ finalText: textEvents.length > 0 ? textEvents[textEvents.length - 1] : undefined,
109
+ usage,
110
+ };
111
+ }