pi-crew 0.9.68 → 0.10.1

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 (217) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/agents/analyst.md +1 -1
  3. package/agents/cold-verifier.md +3 -1
  4. package/agents/critic.md +1 -1
  5. package/agents/executor.md +1 -1
  6. package/agents/explorer.md +1 -1
  7. package/agents/planner.md +1 -1
  8. package/agents/reviewer.md +1 -1
  9. package/agents/security-reviewer.md +1 -1
  10. package/agents/test-engineer.md +1 -1
  11. package/agents/verifier.md +1 -1
  12. package/agents/writer.md +1 -1
  13. package/dist/index.mjs +65838 -60331
  14. package/docs/README.md +2 -0
  15. package/docs/actions-reference.md +31 -0
  16. package/docs/commands-reference.md +17 -6
  17. package/docs/resource-formats.md +13 -0
  18. package/package.json +4 -2
  19. package/schema.json +15 -1
  20. package/scripts/resource-sampler.mjs +36 -2
  21. package/skills/requirements-to-task-packet/SKILL.md +26 -0
  22. package/skills/widget-rendering/SKILL.md +7 -7
  23. package/src/agents/agent-config.ts +2 -1
  24. package/src/agents/discover-agents.ts +23 -14
  25. package/src/config/config-merge.ts +183 -0
  26. package/src/config/config-validation.ts +681 -0
  27. package/src/config/config.ts +22 -864
  28. package/src/config/defaults.ts +35 -1
  29. package/src/config/drift-detector.ts +1 -1
  30. package/src/config/env-vars.ts +691 -0
  31. package/src/config/role-tools.ts +8 -8
  32. package/src/config/sanitize-project-config.ts +172 -0
  33. package/src/config/types.ts +30 -0
  34. package/src/extension/async-notifier.ts +25 -2
  35. package/src/extension/crew-vibes/config.ts +2 -1
  36. package/src/extension/plan-orchestrate.ts +132 -0
  37. package/src/extension/registration/commands/dashboard.ts +158 -0
  38. package/src/extension/registration/commands/index.ts +35 -0
  39. package/src/extension/registration/commands/manage.ts +303 -0
  40. package/src/extension/registration/commands/run.ts +214 -0
  41. package/src/extension/registration/commands/shared.ts +631 -0
  42. package/src/extension/registration/commands/status.ts +60 -0
  43. package/src/extension/registration/commands.ts +13 -1224
  44. package/src/extension/registration/lifecycle-handlers.ts +126 -15
  45. package/src/extension/registration/subagent-tools.ts +218 -9
  46. package/src/extension/rpc-hmac.ts +5 -3
  47. package/src/extension/team-tool/api/heartbeat.ts +47 -10
  48. package/src/extension/team-tool/api/plan-approval.ts +9 -0
  49. package/src/extension/team-tool/api/task-claims.ts +109 -40
  50. package/src/extension/team-tool/cancel.ts +84 -50
  51. package/src/extension/team-tool/dispatch/index.ts +1 -0
  52. package/src/extension/team-tool/dispatch/run.ts +4 -1
  53. package/src/extension/team-tool/doctor.ts +103 -1
  54. package/src/extension/team-tool/orchestrate.ts +66 -1
  55. package/src/extension/team-tool/plans.ts +192 -0
  56. package/src/extension/team-tool/respond.ts +197 -65
  57. package/src/extension/team-tool/run-deadline.ts +16 -1
  58. package/src/extension/team-tool/run-intent.ts +63 -0
  59. package/src/extension/team-tool/run.ts +48 -18
  60. package/src/extension/team-tool/status.ts +84 -26
  61. package/src/extension/team-tool.ts +11 -2
  62. package/src/hooks/registry.ts +1 -6
  63. package/src/i18n.ts +9 -0
  64. package/src/prompt/prompt-runtime.ts +521 -2
  65. package/src/prompt/worker-events-channel.ts +173 -0
  66. package/src/runtime/README.md +8 -8
  67. package/src/runtime/async-runner.ts +7 -3
  68. package/src/runtime/background-runner.ts +42 -14
  69. package/src/runtime/broker/broker-issuer.ts +9 -2
  70. package/src/runtime/broker/crew-broker-tokens.ts +43 -6
  71. package/src/runtime/broker/crew-broker.ts +838 -10
  72. package/src/runtime/broker/wait-status-cache.ts +157 -0
  73. package/src/runtime/budget-enforcement.ts +281 -0
  74. package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
  75. package/src/runtime/child-pi/child-pi-timers.ts +324 -0
  76. package/src/runtime/child-pi/child-pi.ts +97 -201
  77. package/src/runtime/child-pi/mock-fixtures.ts +16 -2
  78. package/src/runtime/crew-agent-records.ts +259 -14
  79. package/src/runtime/delegate-spawn.ts +148 -0
  80. package/src/runtime/deterministic-ast.ts +2 -1
  81. package/src/runtime/dispatch-batch.ts +945 -0
  82. package/src/runtime/finalize-run.ts +557 -0
  83. package/src/runtime/goal-workflow/adaptive-plan.ts +87 -13
  84. package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +3 -2
  85. package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
  86. package/src/runtime/group-join.ts +11 -125
  87. package/src/runtime/live-session/live-session-runtime.ts +26 -1
  88. package/src/runtime/merge-gate.ts +7 -1
  89. package/src/runtime/merge-loop.ts +130 -0
  90. package/src/runtime/model/model-budget-summary.ts +53 -0
  91. package/src/runtime/model/model-fallback.ts +32 -2
  92. package/src/runtime/model/pi-args.ts +10 -0
  93. package/src/runtime/model/provider-extensions.ts +10 -0
  94. package/src/runtime/orphan-worker-registry.ts +1 -1
  95. package/src/runtime/output/output-validator.ts +45 -0
  96. package/src/runtime/parent-guard.ts +3 -1
  97. package/src/runtime/peer-dep.ts +2 -1
  98. package/src/runtime/per-write-validator.ts +0 -5
  99. package/src/runtime/pi-spawn.ts +61 -15
  100. package/src/runtime/plan-approval.ts +125 -0
  101. package/src/runtime/plan-replan.ts +151 -0
  102. package/src/runtime/recovery/checkpoint.ts +0 -18
  103. package/src/runtime/recovery/crash-recovery.ts +95 -46
  104. package/src/runtime/scheduler-context.ts +98 -0
  105. package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
  106. package/src/runtime/scheduling/global-worker-cap.ts +2 -1
  107. package/src/runtime/scheduling/nested-slots.ts +70 -0
  108. package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
  109. package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
  110. package/src/runtime/settings-store.ts +219 -0
  111. package/src/runtime/spawn-policy.ts +217 -0
  112. package/src/runtime/stale-reconciler.ts +87 -6
  113. package/src/runtime/subagent-manager.ts +25 -1
  114. package/src/runtime/task-output-context.ts +230 -9
  115. package/src/runtime/task-packet.ts +23 -1
  116. package/src/runtime/task-runner/child-executor.ts +106 -7
  117. package/src/runtime/task-runner/post-execution.ts +125 -1
  118. package/src/runtime/task-runner/pre-execution.ts +39 -1
  119. package/src/runtime/task-runner/prompt-builder.ts +51 -1
  120. package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
  121. package/src/runtime/task-runner/spec-evidence.ts +403 -0
  122. package/src/runtime/task-runner/state-helpers.ts +26 -24
  123. package/src/runtime/task-runner.ts +11 -0
  124. package/src/runtime/team-runner.ts +129 -1671
  125. package/src/runtime/verification/spec-sandbox.ts +255 -0
  126. package/src/runtime/verification/verification-gates.ts +3 -2
  127. package/src/runtime/verification/verification-worktree.ts +2 -1
  128. package/src/runtime/workflow-phase-advance.ts +100 -0
  129. package/src/runtime/workspace-tree.ts +9 -0
  130. package/src/schema/config-schema.ts +65 -25
  131. package/src/schema/sensitive-config-paths.ts +64 -0
  132. package/src/schema/team-tool-schema.ts +13 -3
  133. package/src/state/README.md +4 -10
  134. package/src/state/atomic-write.ts +20 -3
  135. package/src/state/contracts.ts +38 -0
  136. package/src/state/coordination/mailbox.ts +12 -2
  137. package/src/state/event-log/cursor.ts +223 -0
  138. package/src/state/event-log/event-log-rotation.ts +12 -4
  139. package/src/state/event-log/event-log.ts +152 -369
  140. package/src/state/event-log/sequence-cache.ts +373 -0
  141. package/src/state/event-log/worker-atomic-writer.ts +2 -1
  142. package/src/state/stores/active-run-registry.ts +3 -2
  143. package/src/state/stores/manifest-io.ts +237 -0
  144. package/src/state/stores/ownership-map.ts +162 -0
  145. package/src/state/stores/plan-store.ts +241 -0
  146. package/src/state/stores/run-cache.ts +0 -90
  147. package/src/state/stores/spec-store.ts +189 -0
  148. package/src/state/stores/state-store.ts +66 -229
  149. package/src/state/types.ts +197 -0
  150. package/src/ui/dashboard-panes/plan-pane.ts +136 -0
  151. package/src/ui/dashboard-panes/progress-pane.ts +6 -0
  152. package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
  153. package/src/ui/heartbeat-aggregator.ts +9 -1
  154. package/src/ui/keybinding-map.ts +54 -13
  155. package/src/ui/powerbar-publisher.ts +52 -1
  156. package/src/ui/run-dashboard.ts +31 -5
  157. package/src/ui/run-snapshot-cache.ts +57 -30
  158. package/src/ui/snapshot-types.ts +6 -1
  159. package/src/ui/widget/widget-renderer.ts +9 -1
  160. package/src/utils/file-coalescer.ts +0 -4
  161. package/src/utils/fs-errno.ts +66 -0
  162. package/src/utils/fs-watch.ts +1 -1
  163. package/src/utils/internal-error.ts +3 -1
  164. package/src/utils/paths.ts +11 -3
  165. package/src/utils/task-name-generator.ts +1 -8
  166. package/src/workflows/discover-workflows.ts +19 -2
  167. package/src/workflows/validate-workflow.ts +7 -1
  168. package/src/workflows/workflow-config.ts +10 -0
  169. package/src/workflows/workflow-serializer.ts +3 -0
  170. package/src/worktree/worktree-manager.ts +22 -0
  171. package/src/agents/agent-search.ts +0 -98
  172. package/src/benchmark/benchmark-runner.ts +0 -313
  173. package/src/benchmark/feedback-loop.ts +0 -73
  174. package/src/config/resilient-parser.ts +0 -117
  175. package/src/extension/crew-vibes/cat-frames.ts +0 -18
  176. package/src/extension/result-watcher.ts +0 -139
  177. package/src/observability/exporters/prometheus-exporter.ts +0 -54
  178. package/src/observability/metric-retention.ts +0 -64
  179. package/src/runtime/compaction/compaction-summary.ts +0 -278
  180. package/src/runtime/errors/crew-errors.ts +0 -162
  181. package/src/runtime/live-session/intercom-bridge.ts +0 -187
  182. package/src/runtime/loop-gates.ts +0 -128
  183. package/src/runtime/metric-parser.ts +0 -36
  184. package/src/runtime/output/stream-preview.ts +0 -184
  185. package/src/runtime/output/tool-progress.ts +0 -278
  186. package/src/runtime/phase-tracker.ts +0 -385
  187. package/src/runtime/pipeline-runner.ts +0 -523
  188. package/src/runtime/process/process-lifecycle.ts +0 -491
  189. package/src/runtime/recovery/retry-runner.ts +0 -330
  190. package/src/runtime/run-drift.ts +0 -219
  191. package/src/runtime/task-quality.ts +0 -199
  192. package/src/runtime/task-runner/run-projection.ts +0 -128
  193. package/src/runtime/verification/post-checks.ts +0 -142
  194. package/src/state/coordination/schedule.ts +0 -166
  195. package/src/state/event-log/jsonl-writer.ts +0 -115
  196. package/src/state/hook-instinct-bridge.ts +0 -94
  197. package/src/state/hook-integrations.ts +0 -51
  198. package/src/state/session-state-map.ts +0 -51
  199. package/src/state/stores/blob-store.ts +0 -308
  200. package/src/state/stores/instinct-store.ts +0 -275
  201. package/src/state/stores/observation-store.ts +0 -176
  202. package/src/state/tiered-eval.ts +0 -480
  203. package/src/state/types-eval.ts +0 -58
  204. package/src/tools/safe-bash-extension.ts +0 -54
  205. package/src/tools/safe-bash.ts +0 -505
  206. package/src/ui/agent-management-overlay.ts +0 -160
  207. package/src/ui/crew-footer.ts +0 -102
  208. package/src/ui/crew-select-list.ts +0 -114
  209. package/src/ui/dashboard-panes/capability-pane.ts +0 -77
  210. package/src/ui/transcript-entries.ts +0 -256
  211. package/src/utils/conflict-detect.ts +0 -721
  212. package/src/utils/fingerprint.ts +0 -180
  213. package/src/utils/gh-protocol.ts +0 -556
  214. package/src/utils/project-detector.ts +0 -160
  215. package/src/utils/sse-parser.ts +0 -131
  216. package/src/workflows/cost-estimator.ts +0 -34
  217. package/src/workflows/intermediate-store.ts +0 -166
@@ -0,0 +1,631 @@
1
+ import * as path from "node:path";
2
+ import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { loadConfig } from "../../../config/config.ts";
4
+ import { DEFAULT_UI } from "../../../config/defaults.ts";
5
+ import type { MetricRegistry } from "../../../observability/metric-registry.ts";
6
+ import { listRecentDiagnostic } from "../../../runtime/diagnostic-export.ts";
7
+ import { isPlanApprovalPendingEffective } from "../../../runtime/plan-approval.ts";
8
+ import type { TeamAction } from "../../../schema/team-tool-schema.ts";
9
+ import { loadRunManifestById } from "../../../state/stores/state-store.ts";
10
+ import type { TeamRunManifest } from "../../../state/types.ts";
11
+ import { getKeybindingOverrideWarnings } from "../../../ui/keybinding-map.ts";
12
+ import type { AnimatedMascot as AnimatedMascotType } from "../../../ui/mascot.ts";
13
+ import type { AgentPickerOverlay as AgentPickerOverlayType } from "../../../ui/overlays/agent-picker-overlay.ts";
14
+ import type { ConfirmOptions, ConfirmOverlay as ConfirmOverlayType } from "../../../ui/overlays/confirm-overlay.ts";
15
+ import type {
16
+ MailboxComposeOverlay as MailboxComposeOverlayType,
17
+ MailboxComposeResult,
18
+ } from "../../../ui/overlays/mailbox-compose-overlay.ts";
19
+ import type { MailboxAction, MailboxDetailOverlay as MailboxDetailOverlayType } from "../../../ui/overlays/mailbox-detail-overlay.ts";
20
+ import { requestRenderTarget } from "../../../ui/pi-ui-compat.ts";
21
+ import {
22
+ dispatchDiagnosticExport,
23
+ dispatchHealthRecovery,
24
+ dispatchKillStaleWorkers,
25
+ dispatchMailboxAck,
26
+ dispatchMailboxAckAll,
27
+ dispatchMailboxCompose,
28
+ dispatchMailboxNudge,
29
+ } from "../../../ui/run-action-dispatcher.ts";
30
+ import type { RunDashboardSelection, RunDashboard as RunDashboardType } from "../../../ui/run-dashboard.ts";
31
+ import type { createRunSnapshotCache } from "../../../ui/run-snapshot-cache.ts";
32
+ import type { DurableTextViewer as DurableTextViewerType } from "../../../ui/transcript-viewer.ts";
33
+ import { withSessionId } from "../../team-tool/context.ts";
34
+ // Lazy-loaded: team-tool.ts pulls in entire runtime chain (1.4s+).
35
+ import type { handleTeamTool as HandleTeamToolFn } from "../../team-tool.ts";
36
+ import { commandText, notifyCommandResult } from "../command-utils.ts";
37
+ import type { UiState } from "../ui.ts";
38
+ import { openLiveConversation, openTranscriptViewer } from "../viewers.ts";
39
+
40
+ let _cachedHandleTeamTool: typeof HandleTeamToolFn | undefined;
41
+ let _handleTeamToolPromise: Promise<typeof HandleTeamToolFn> | undefined;
42
+ export async function handleTeamTool(
43
+ params: Parameters<typeof HandleTeamToolFn>[0],
44
+ ctx: Parameters<typeof HandleTeamToolFn>[1],
45
+ ): Promise<Awaited<ReturnType<typeof HandleTeamToolFn>>> {
46
+ if (!_cachedHandleTeamTool) {
47
+ if (!_handleTeamToolPromise) {
48
+ _handleTeamToolPromise = import("../../team-tool.ts").then((mod) => {
49
+ _cachedHandleTeamTool = mod.handleTeamTool;
50
+ return mod.handleTeamTool;
51
+ });
52
+ }
53
+ const fn = await _handleTeamToolPromise;
54
+ return fn(params, ctx);
55
+ }
56
+ return _cachedHandleTeamTool(params, ctx);
57
+ }
58
+
59
+ /**
60
+ * TEST SEAM (STEP 1.9a) — substitute the lazy-loaded team-tool facade.
61
+ * Production `handleTeamTool` populates `_cachedHandleTeamTool` on first use
62
+ * via `import("../../team-tool.ts")` (1.4s+ runtime chain). This lets unit tests
63
+ * inject a recording stub and exercise command handlers without importing the
64
+ * chain. No production behavior change: the lazy-import path is untouched when
65
+ * this is never called, and handlers always resolve through the same cache.
66
+ */
67
+ export function __test__setHandleTeamTool(fn: typeof HandleTeamToolFn | undefined): void {
68
+ _cachedHandleTeamTool = fn;
69
+ _handleTeamToolPromise = undefined;
70
+ }
71
+
72
+ export interface RegisterTeamCommandsDeps {
73
+ startForegroundRun: (ctx: ExtensionContext, runner: (signal?: AbortSignal) => Promise<void>, runId?: string) => void;
74
+ abortForegroundRun: (runId: string) => boolean;
75
+ openLiveSidebar: (ctx: ExtensionContext, runId: string) => void;
76
+ getManifestCache: (cwd: string) => {
77
+ list(max?: number): TeamRunManifest[];
78
+ };
79
+ getRunSnapshotCache?: (cwd: string) => ReturnType<typeof createRunSnapshotCache>;
80
+ getMetricRegistry?: () => MetricRegistry | undefined;
81
+ uiState?: UiState;
82
+ dismissNotifications?: () => void;
83
+ }
84
+
85
+ // Lazy-loaded UI module cache — avoids importing 900ms+ of UI at Pi startup.
86
+ // These modules are only needed when user invokes /crew commands.
87
+ let _uiCache:
88
+ | {
89
+ RunDashboard: typeof RunDashboardType;
90
+ DurableTextViewer: typeof DurableTextViewerType;
91
+ ConfirmOverlay: typeof ConfirmOverlayType;
92
+ MailboxDetailOverlay: typeof MailboxDetailOverlayType;
93
+ MailboxComposeOverlay: typeof MailboxComposeOverlayType;
94
+ AgentPickerOverlay: typeof AgentPickerOverlayType;
95
+ AnimatedMascot: typeof AnimatedMascotType;
96
+ }
97
+ | undefined;
98
+ let _uiCachePromise: Promise<NonNullable<typeof _uiCache>> | undefined;
99
+ export async function ui(): Promise<NonNullable<typeof _uiCache>> {
100
+ if (!_uiCache) {
101
+ if (!_uiCachePromise) {
102
+ _uiCachePromise = (async () => {
103
+ const [rd, tv, co, md, mc, ap, ma] = await Promise.all([
104
+ import("../../../ui/run-dashboard.ts"),
105
+ import("../../../ui/transcript-viewer.ts"),
106
+ import("../../../ui/overlays/confirm-overlay.ts"),
107
+ import("../../../ui/overlays/mailbox-detail-overlay.ts"),
108
+ import("../../../ui/overlays/mailbox-compose-overlay.ts"),
109
+ import("../../../ui/overlays/agent-picker-overlay.ts"),
110
+ import("../../../ui/mascot.ts"),
111
+ ]);
112
+ const cache = {
113
+ RunDashboard: rd.RunDashboard,
114
+ DurableTextViewer: tv.DurableTextViewer,
115
+ ConfirmOverlay: co.ConfirmOverlay,
116
+ MailboxDetailOverlay: md.MailboxDetailOverlay,
117
+ MailboxComposeOverlay: mc.MailboxComposeOverlay,
118
+ AgentPickerOverlay: ap.AgentPickerOverlay,
119
+ AnimatedMascot: ma.AnimatedMascot,
120
+ };
121
+ _uiCache = cache;
122
+ return cache;
123
+ })();
124
+ }
125
+ return _uiCachePromise;
126
+ }
127
+ return _uiCache;
128
+ }
129
+
130
+ async function openConfirm(ctx: ExtensionCommandContext, options: ConfirmOptions): Promise<boolean> {
131
+ if (!ctx.hasUI) return false;
132
+ const { ConfirmOverlay } = await ui();
133
+ return await ctx.ui.custom<boolean>((_tui, theme, _keybindings, done) => new ConfirmOverlay(options, done, theme), {
134
+ overlay: true,
135
+ overlayOptions: { width: 64, maxHeight: "70%", anchor: "center" },
136
+ });
137
+ }
138
+
139
+ async function handleMailboxDashboardAction(ctx: ExtensionCommandContext, runId: string): Promise<void> {
140
+ if (!ctx.hasUI) return;
141
+ const { MailboxDetailOverlay } = await ui();
142
+ const action = await ctx.ui.custom<MailboxAction | undefined>(
143
+ (_tui, theme, _keybindings, done) => new MailboxDetailOverlay({ runId, cwd: ctx.cwd, done, theme }),
144
+ {
145
+ overlay: true,
146
+ overlayOptions: {
147
+ width: "90%",
148
+ maxHeight: "85%",
149
+ anchor: "center",
150
+ },
151
+ },
152
+ );
153
+ if (!action || action.type === "close") return;
154
+ let resultMessage: string | undefined;
155
+ let ok = true;
156
+ if (action.type === "ack") {
157
+ const result = await dispatchMailboxAck(ctx as ExtensionContext, runId, action.messageId);
158
+ ok = result.ok;
159
+ resultMessage = result.message;
160
+ } else if (action.type === "ackAll") {
161
+ const confirmed = await openConfirm(ctx, {
162
+ title: "Acknowledge all unread messages?",
163
+ body: "This cannot be undone. Y=ack all, N=cancel.",
164
+ dangerLevel: "medium",
165
+ defaultAction: "cancel",
166
+ });
167
+ if (!confirmed) return;
168
+ const result = await dispatchMailboxAckAll(ctx as ExtensionContext, runId);
169
+ ok = result.ok;
170
+ resultMessage = result.message;
171
+ } else if (action.type === "compose") {
172
+ const { MailboxComposeOverlay } = await ui();
173
+ const compose = await ctx.ui.custom<MailboxComposeResult>(
174
+ (_tui, theme, _keybindings, done) => new MailboxComposeOverlay({ done, theme }),
175
+ {
176
+ overlay: true,
177
+ overlayOptions: {
178
+ width: "90%",
179
+ maxHeight: "85%",
180
+ anchor: "center",
181
+ },
182
+ },
183
+ );
184
+ if (compose.type === "cancel") return;
185
+ const result = await dispatchMailboxCompose(ctx as ExtensionContext, runId, compose.payload);
186
+ ok = result.ok;
187
+ resultMessage = result.message;
188
+ } else if (action.type === "nudge") {
189
+ let agentId = action.agentId;
190
+ if (!agentId) {
191
+ const { AgentPickerOverlay } = await ui();
192
+ const picked = await ctx.ui.custom<{ agentId: string } | undefined>(
193
+ (_tui, theme, _keybindings, done) =>
194
+ new AgentPickerOverlay({
195
+ cwd: ctx.cwd,
196
+ runId,
197
+ done,
198
+ theme,
199
+ }),
200
+ {
201
+ overlay: true,
202
+ overlayOptions: {
203
+ width: 72,
204
+ maxHeight: "75%",
205
+ anchor: "center",
206
+ },
207
+ },
208
+ );
209
+ agentId = picked?.agentId;
210
+ }
211
+ if (!agentId) return;
212
+ const result = await dispatchMailboxNudge(
213
+ ctx as ExtensionContext,
214
+ runId,
215
+ agentId,
216
+ "Please report your current status, blocker, or smallest next step.",
217
+ );
218
+ ok = result.ok;
219
+ resultMessage = result.message;
220
+ }
221
+ depsNotify(ctx, resultMessage ?? "Mailbox action complete.", ok ? "info" : "error");
222
+ }
223
+
224
+ function depsNotify(ctx: ExtensionCommandContext, message: string, level: "info" | "warning" | "error"): void {
225
+ if (!ctx.hasUI) return;
226
+ ctx.ui.notify(message, level);
227
+ }
228
+
229
+ export function teamCommandContext(ctx: ExtensionCommandContext): ExtensionCommandContext & { sessionId?: string } {
230
+ return withSessionId(ctx);
231
+ }
232
+
233
+ /**
234
+ * Open the pi-crew settings overlay (config editor + theme picker).
235
+ *
236
+ * Extracted from the `team-settings` command so it is reusable from a
237
+ * keyboard shortcut. Takes the base `ExtensionContext` (the shortcut
238
+ * handler's context) — uses only `hasUI`, `cwd`, and `ui` fields, so both
239
+ * `ExtensionContext` and `ExtensionCommandContext` satisfy it.
240
+ */
241
+ export async function openTeamSettingsOverlay(ctx: ExtensionContext): Promise<void> {
242
+ if (!ctx.hasUI) return;
243
+ const [{ updateConfig, parseConfig }, { asCrewTheme }, { createSettingsOverlay }] = await Promise.all([
244
+ import("../../../config/config.ts"),
245
+ import("../../../ui/theme-adapter.ts"),
246
+ import("../../../ui/settings-overlay.ts"),
247
+ ]);
248
+ const loaded = loadConfig(ctx.cwd);
249
+ const config = loaded.config as Record<string, unknown>;
250
+ await ctx.ui.custom<undefined>(
251
+ (_tui, _theme, _keybindings, done) => {
252
+ const theme = asCrewTheme(_theme);
253
+ const { overlay } = createSettingsOverlay(
254
+ config,
255
+ theme,
256
+ (id: string, value: unknown) => {
257
+ try {
258
+ const patch: Record<string, unknown> = {};
259
+ const keys = id.split(".");
260
+ let target: Record<string, unknown> = patch;
261
+ for (let i = 0; i < keys.length - 1; i++) {
262
+ if (!target[keys[i]!] || typeof target[keys[i]!] !== "object") target[keys[i]!] = {};
263
+ target = target[keys[i]!] as Record<string, unknown>;
264
+ }
265
+ target[keys[keys.length - 1]!] = value;
266
+ if (value === undefined) {
267
+ updateConfig({}, { unsetPaths: [id] });
268
+ } else {
269
+ updateConfig(parseConfig(patch));
270
+ }
271
+ } catch (error) {
272
+ ctx.ui.notify(`Failed to save: ${error instanceof Error ? error.message : String(error)}`, "error");
273
+ }
274
+ },
275
+ () => done(undefined),
276
+ async (action: string, value: unknown) => {
277
+ // Action callbacks (Pi theme switch) write to a different store
278
+ // than pi-crew config (e.g. ~/.pi/agent/settings.json).
279
+ try {
280
+ if (action === "piTheme" && typeof value === "string") {
281
+ // Live theme switch: ctx.ui.setTheme() swaps the global theme,
282
+ // persists it to settings.json, and triggers a UI redraw — no
283
+ // restart needed. Falls back to file-write + restart hint if
284
+ // the live API is unavailable (e.g. non-TUI mode).
285
+ if (typeof ctx.ui.setTheme === "function") {
286
+ const res = ctx.ui.setTheme(value);
287
+ if (res.success) {
288
+ ctx.ui.notify(`Theme: ${value} (applied live)`, "info");
289
+ } else {
290
+ // LAZY: defer dynamic import of ../../ui/theme-discovery.ts to its call site.
291
+ const { setPiTheme } = await import("../../../ui/theme-discovery.ts");
292
+ setPiTheme(value);
293
+ ctx.ui.notify(
294
+ `Theme saved as '${value}' but failed to apply: ${res.error ?? "unknown"}. Restart Pi.`,
295
+ "warning",
296
+ );
297
+ }
298
+ } else {
299
+ // LAZY: defer dynamic import of ../../ui/theme-discovery.ts to its call site.
300
+ const { setPiTheme } = await import("../../../ui/theme-discovery.ts");
301
+ setPiTheme(value);
302
+ ctx.ui.notify(`Pi theme set to '${value}'. Restart Pi to apply.`, "info");
303
+ }
304
+ }
305
+ } catch (error) {
306
+ ctx.ui.notify(`Failed: ${error instanceof Error ? error.message : String(error)}`, "error");
307
+ }
308
+ },
309
+ );
310
+ return overlay;
311
+ },
312
+ {
313
+ overlay: true,
314
+ overlayOptions: {
315
+ width: "90%",
316
+ maxHeight: "85%",
317
+ anchor: "center",
318
+ },
319
+ },
320
+ );
321
+ }
322
+
323
+ async function handleHealthDashboardAction(ctx: ExtensionCommandContext, selection: RunDashboardSelection): Promise<void> {
324
+ const loaded = loadRunManifestById(ctx.cwd, selection.runId); // NOTE: no withRunLock - best-effort only; concurrent writes may cause inconsistency
325
+ if (!loaded) {
326
+ depsNotify(ctx, `Run '${selection.runId}' not found.`, "error");
327
+ return;
328
+ }
329
+ if (selection.action === "health-recovery") {
330
+ if (loaded.manifest.async) {
331
+ depsNotify(ctx, "Recovery is only available for foreground runs.", "warning");
332
+ return;
333
+ }
334
+ const confirmed = await openConfirm(ctx, {
335
+ title: "Interrupt foreground run?",
336
+ body: "Tasks may be marked failed. Y=interrupt, N=cancel.",
337
+ dangerLevel: "high",
338
+ defaultAction: "cancel",
339
+ });
340
+ if (!confirmed) return;
341
+ const result = await dispatchHealthRecovery(ctx as ExtensionContext, selection.runId);
342
+ depsNotify(ctx, result.message, result.ok ? "info" : "error");
343
+ return;
344
+ }
345
+ if (selection.action === "health-kill-stale") {
346
+ const confirmed = await openConfirm(ctx, {
347
+ title: "Mark stale workers dead?",
348
+ body: "This updates worker heartbeat state. Y=mark dead, N=cancel.",
349
+ dangerLevel: "medium",
350
+ defaultAction: "cancel",
351
+ });
352
+ if (!confirmed) return;
353
+ const result = await dispatchKillStaleWorkers(ctx as ExtensionContext, selection.runId);
354
+ depsNotify(ctx, result.message, result.ok ? "info" : "error");
355
+ return;
356
+ }
357
+ if (selection.action === "health-diagnostic-export") {
358
+ const diagDir = path.join(loaded.manifest.artifactsRoot, "diagnostic");
359
+ const recent = listRecentDiagnostic(diagDir, 60_000);
360
+ if (recent) {
361
+ const confirmed = await openConfirm(ctx, {
362
+ title: "Recent diagnostic exists",
363
+ body: `File ${recent} was created <1min ago. Export another diagnostic?`,
364
+ defaultAction: "cancel",
365
+ });
366
+ if (!confirmed) return;
367
+ }
368
+ const result = await dispatchDiagnosticExport(ctx as ExtensionContext, selection.runId, {
369
+ registry: depsRef?.getMetricRegistry?.(),
370
+ });
371
+ depsNotify(ctx, result.message, result.ok ? "info" : "error");
372
+ }
373
+ }
374
+
375
+ /**
376
+ * WP-3 (H4-subset): dashboard plan-approval actions (A approve / n deny in
377
+ * the progress pane). Modeled on handleHealthDashboardAction above: reload the
378
+ * manifest, pre-check pending (the backend api op re-validates under
379
+ * withRunLock — this pre-check is UX-only), dispatch the EXISTING team api op,
380
+ * then notify. The caller invalidates the snapshot cache afterwards.
381
+ */
382
+ async function handlePlanDashboardAction(ctx: ExtensionCommandContext, selection: RunDashboardSelection): Promise<void> {
383
+ // F3 decision (WP-3 review round 1, documented): NO manifest.async gate —
384
+ // unlike health-recovery (which interrupts the foreground loop and is
385
+ // foreground-only by necessity). Async/background runs park on plan approval
386
+ // exactly like foreground runs (background-runner executeTeamRun → plan
387
+ // gate), so their approvals MUST be decidable from the dashboard. Deny on
388
+ // an async run terminates tasks via the SAME backend path as chat `team api
389
+ // cancel-plan` (parity), guarded by the medium-danger confirm below + the
390
+ // backend's withRunLock re-validation.
391
+ const loaded = loadRunManifestById(ctx.cwd, selection.runId); // NOTE: no withRunLock - best-effort only; concurrent writes may cause inconsistency
392
+ if (!loaded) {
393
+ depsNotify(ctx, `Run '${selection.runId}' not found.`, "error");
394
+ return;
395
+ }
396
+ if (!isPlanApprovalPendingEffective(loaded.manifest)) {
397
+ depsNotify(ctx, "no pending plan approval", "warning");
398
+ return;
399
+ }
400
+ if (selection.action === "plan-deny") {
401
+ // cancel-plan KILLS tasks, so deny gets a medium-danger confirm.
402
+ // Keystroke math (plan AC ≤ 2 per action): approve = "A" → 1 keystroke
403
+ // (dispatched directly below, no confirm); deny = "n" + confirm = 2.
404
+ // ConfirmOverlay.handleInput treats n/N as CANCEL in its own overlay,
405
+ // so the copy must instruct Y-to-confirm — pressing "n" twice would
406
+ // abort instead of confirming.
407
+ const confirmed = await openConfirm(ctx, {
408
+ title: "Cancel plan and kill tasks?",
409
+ body: "Y=cancel plan and kill tasks, N=abort.",
410
+ dangerLevel: "medium",
411
+ defaultAction: "cancel",
412
+ });
413
+ if (!confirmed) return;
414
+ }
415
+ const operation = selection.action === "plan-approve" ? "approve-plan" : "cancel-plan";
416
+ const result = await handleTeamTool(
417
+ {
418
+ action: "api",
419
+ runId: selection.runId,
420
+ config: { operation },
421
+ },
422
+ teamCommandContext(ctx),
423
+ );
424
+ // F4 (WP-3 review round 1): notifyCommandResult hardcodes level "info",
425
+ // which downgraded backend rejections (e.g. the deny TOCTOU tail — approval
426
+ // answered between keypress and dispatch, refused under withRunLock) to
427
+ // info toasts. Surface isError results at their true level.
428
+ const text = commandText(result);
429
+ depsNotify(ctx, text.length > 800 ? `${text.slice(0, 797)}...` : text, result.isError ? "error" : "info");
430
+ }
431
+
432
+ let depsRef: RegisterTeamCommandsDeps | undefined;
433
+
434
+ /**
435
+ * Internal setter for `depsRef` (Phase 2.1 split). ESM import bindings are
436
+ * read-only, so `registerTeamCommands` in index.ts cannot assign to the
437
+ * shared binding directly; this setter preserves the original single-module
438
+ * behavior (module-level state set once at registration).
439
+ */
440
+ export function setTeamCommandsDeps(deps: RegisterTeamCommandsDeps): void {
441
+ depsRef = deps;
442
+ }
443
+
444
+ /**
445
+ * Open the pi-crew run dashboard overlay and run its action loop.
446
+ *
447
+ * Extracted verbatim from the `team-dashboard` command so it is reusable from
448
+ * a keyboard shortcut (alt+c, see crew-shortcuts.ts). Takes the base
449
+ * `ExtensionContext` (the shortcut handler's context) — uses only `hasUI`,
450
+ * `cwd`, `ui`, and `sessionManager` fields, so both `ExtensionContext` and
451
+ * `ExtensionCommandContext` satisfy it. Reads run caches via the module-level
452
+ * `depsRef` (set by `registerTeamCommands`), so it is a no-op if commands
453
+ * have not been registered yet. `deps` is captured into a local const so the
454
+ * non-undefined narrowing survives the awaited overlay call.
455
+ *
456
+ * The dashboard action helpers (handleMailboxDashboardAction, the viewers,
457
+ * notifyCommandResult, teamCommandContext/handleTeamTool) are declared for
458
+ * `ExtensionCommandContext` but only ever read base `ExtensionContext` fields
459
+ * (verified). The keyboard-shortcut path supplies an `ExtensionContext`, so we
460
+ * bridge those over-typed helpers with a single cast rather than relaxing
461
+ * signatures across several modules (some outside this file's scope).
462
+ */
463
+ export async function openTeamDashboard(ctx: ExtensionContext): Promise<void> {
464
+ if (!ctx.hasUI) return;
465
+ const deps = depsRef;
466
+ if (!deps) return;
467
+ if (deps.uiState) deps.uiState.dashboardOpen = true;
468
+ const cmdCtx = ctx as ExtensionCommandContext;
469
+ // F1 (WP-3 review round 1): keybinding-override collisions are reverted to
470
+ // defaults by computeEffectiveBindings to keep dispatch unambiguous — but
471
+ // the warning API (getKeybindingOverrideWarnings) previously had NO src
472
+ // consumer, so users whose overrides claimed the new progress-pane keys
473
+ // ("A"/"n") got a silent, persistent keybinding break. Surface the revert
474
+ // once per dashboard open instead.
475
+ const keyWarnings = getKeybindingOverrideWarnings();
476
+ if (keyWarnings.length > 0) {
477
+ depsNotify(cmdCtx, `keybindings reverted to defaults: ${keyWarnings.join("; ")}`, "warning");
478
+ }
479
+ for (;;) {
480
+ // Extract sessionId for workspace-scoped filtering
481
+ const sessionId = cmdCtx.sessionManager?.getSessionId?.();
482
+ const runs = deps.getManifestCache(cmdCtx.cwd).list(50);
483
+ const uiConfig = loadConfig(cmdCtx.cwd).config.ui;
484
+ const rightPanel = (uiConfig?.dashboardPlacement ?? DEFAULT_UI.dashboardPlacement) === "right";
485
+ const width = rightPanel ? Math.min(90, Math.max(40, uiConfig?.dashboardWidth ?? DEFAULT_UI.dashboardWidth)) : "90%";
486
+ const { RunDashboard } = await ui();
487
+ const selection = await cmdCtx.ui.custom<RunDashboardSelection | undefined>(
488
+ (tui, theme, _keybindings, done) =>
489
+ new RunDashboard(runs, done, theme, {
490
+ placement: rightPanel ? "right" : "center",
491
+ showModel: uiConfig?.showModel,
492
+ showTokens: uiConfig?.showTokens,
493
+ showTools: uiConfig?.showTools,
494
+ snapshotCache: deps.getRunSnapshotCache?.(cmdCtx.cwd),
495
+ runProvider: () => deps.getManifestCache(cmdCtx.cwd).list(50),
496
+ registry: deps.getMetricRegistry?.(),
497
+ workspaceId: sessionId,
498
+ requestRender: () => requestRenderTarget(tui),
499
+ }),
500
+ {
501
+ overlay: true,
502
+ overlayOptions: rightPanel
503
+ ? {
504
+ width,
505
+ minWidth: 40,
506
+ maxHeight: "100%",
507
+ anchor: "top-right",
508
+ offsetX: 0,
509
+ offsetY: 0,
510
+ margin: { top: 0, right: 0, bottom: 0, left: 0 },
511
+ }
512
+ : { width, maxHeight: "90%", anchor: "center", margin: 2 },
513
+ },
514
+ );
515
+ if (!selection) break;
516
+ if (selection.action === "reload") continue;
517
+ if (selection.action === "notifications-dismiss") {
518
+ deps.dismissNotifications?.();
519
+ cmdCtx.ui.notify("pi-crew notifications dismissed.", "info");
520
+ continue;
521
+ }
522
+ if (selection.action === "mailbox-detail") {
523
+ await handleMailboxDashboardAction(cmdCtx, selection.runId);
524
+ deps.getRunSnapshotCache?.(cmdCtx.cwd).invalidate(selection.runId);
525
+ continue;
526
+ }
527
+ if (
528
+ selection.action === "health-recovery" ||
529
+ selection.action === "health-kill-stale" ||
530
+ selection.action === "health-diagnostic-export"
531
+ ) {
532
+ await handleHealthDashboardAction(cmdCtx, selection);
533
+ deps.getRunSnapshotCache?.(cmdCtx.cwd).invalidate(selection.runId);
534
+ continue;
535
+ }
536
+ if (selection.action === "plan-approve" || selection.action === "plan-deny") {
537
+ await handlePlanDashboardAction(cmdCtx, selection);
538
+ deps.getRunSnapshotCache?.(cmdCtx.cwd).invalidate(selection.runId);
539
+ continue;
540
+ }
541
+ if (selection.action === "agent-transcript" && (await openTranscriptViewer(cmdCtx, selection.runId))) continue;
542
+ if (selection.action === "agent-live" && (await openLiveConversation(cmdCtx, selection.runId))) continue;
543
+ if (selection.action === "agent-live") {
544
+ await notifyCommandResult(
545
+ cmdCtx,
546
+ commandText({
547
+ content: [
548
+ {
549
+ type: "text",
550
+ text: "No live agent found for this run.",
551
+ },
552
+ ],
553
+ }),
554
+ );
555
+ continue;
556
+ }
557
+ const result =
558
+ selection.action === "api"
559
+ ? await handleTeamTool(
560
+ {
561
+ action: "api",
562
+ runId: selection.runId,
563
+ config: { operation: "read-manifest" },
564
+ },
565
+ teamCommandContext(cmdCtx),
566
+ )
567
+ : selection.action === "agents"
568
+ ? await handleTeamTool(
569
+ {
570
+ action: "api",
571
+ runId: selection.runId,
572
+ config: { operation: "agent-dashboard" },
573
+ },
574
+ teamCommandContext(cmdCtx),
575
+ )
576
+ : selection.action === "mailbox"
577
+ ? await handleTeamTool(
578
+ {
579
+ action: "api",
580
+ runId: selection.runId,
581
+ config: { operation: "read-mailbox" },
582
+ },
583
+ teamCommandContext(cmdCtx),
584
+ )
585
+ : selection.action === "agent-events"
586
+ ? await handleTeamTool(
587
+ {
588
+ action: "api",
589
+ runId: selection.runId,
590
+ config: {
591
+ operation: "read-agent-events",
592
+ limit: 50,
593
+ },
594
+ },
595
+ teamCommandContext(cmdCtx),
596
+ )
597
+ : selection.action === "agent-output"
598
+ ? await handleTeamTool(
599
+ {
600
+ action: "api",
601
+ runId: selection.runId,
602
+ config: {
603
+ operation: "read-agent-output",
604
+ maxBytes: 32_000,
605
+ },
606
+ },
607
+ teamCommandContext(cmdCtx),
608
+ )
609
+ : selection.action === "agent-transcript"
610
+ ? await handleTeamTool(
611
+ {
612
+ action: "api",
613
+ runId: selection.runId,
614
+ config: {
615
+ operation: "read-agent-transcript",
616
+ },
617
+ },
618
+ teamCommandContext(cmdCtx),
619
+ )
620
+ : await handleTeamTool(
621
+ {
622
+ action: selection.action as TeamAction,
623
+ runId: selection.runId,
624
+ },
625
+ teamCommandContext(cmdCtx),
626
+ );
627
+ await notifyCommandResult(cmdCtx, commandText(result));
628
+ break;
629
+ }
630
+ if (deps.uiState) deps.uiState.dashboardOpen = false;
631
+ }
@@ -0,0 +1,60 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { suggestRunIds } from "../../command-completions.ts";
3
+ import { piTeamsHelp } from "../../help.ts";
4
+ import { commandText, notifyCommandResult } from "../command-utils.ts";
5
+ import type { RegisterTeamCommandsDeps } from "./shared.ts";
6
+ import { handleTeamTool, teamCommandContext } from "./shared.ts";
7
+
8
+ export function registerStatusCommands(pi: ExtensionAPI, deps: RegisterTeamCommandsDeps): void {
9
+ pi.registerCommand("teams", {
10
+ description: "List pi-crew teams, workflows, and agents",
11
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
12
+ const result = await handleTeamTool({ action: "list" }, teamCommandContext(ctx));
13
+ await notifyCommandResult(ctx, commandText(result));
14
+ },
15
+ });
16
+
17
+ for (const [name, action, description] of [
18
+ ["team-status", "status", "Show pi-crew run status"],
19
+ ["team-summary", "summary", "Show pi-crew run summary"],
20
+ ["team-events", "events", "Show full pi-crew event log for a run"],
21
+ ["team-artifacts", "artifacts", "List pi-crew artifacts for a run"],
22
+ ["team-worktrees", "worktrees", "List pi-crew worktrees for a run"],
23
+ ] as const) {
24
+ pi.registerCommand(name, {
25
+ description,
26
+ // Round 13 UX: suggest recent run IDs for Tab-completion.
27
+ getArgumentCompletions: (argumentPrefix: string) => suggestRunIds(argumentPrefix),
28
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
29
+ const runId = args.trim() || undefined;
30
+ const result = await handleTeamTool(
31
+ { action, runId },
32
+ {
33
+ ...teamCommandContext(ctx),
34
+ getRunSnapshotCache: deps.getRunSnapshotCache,
35
+ },
36
+ );
37
+ await notifyCommandResult(ctx, commandText(result));
38
+ },
39
+ });
40
+ }
41
+
42
+ for (const [name, action, description] of [
43
+ ["team-validate", "validate", "Validate pi-crew agents, teams, and workflows"],
44
+ ["team-doctor", "doctor", "Check pi-crew installation and discovery readiness"],
45
+ ] as const)
46
+ pi.registerCommand(name, {
47
+ description,
48
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
49
+ const result = await handleTeamTool({ action }, teamCommandContext(ctx));
50
+ await notifyCommandResult(ctx, commandText(result));
51
+ },
52
+ });
53
+
54
+ pi.registerCommand("team-help", {
55
+ description: "Show pi-crew command help",
56
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
57
+ await notifyCommandResult(ctx, piTeamsHelp());
58
+ },
59
+ });
60
+ }