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,305 +1,305 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import type { AgentConfig } from "../agents/agent-config.ts";
4
- import type { CrewRuntimeConfig } from "../config/config.ts";
5
- import type { TeamRunManifest, TeamTaskState, UsageState } from "../state/types.ts";
6
- import { buildMemoryBlock } from "./agent-memory.ts";
7
- import { registerLiveAgent, updateLiveAgentStatus } from "./live-agent-manager.ts";
8
- import { applyLiveAgentControlRequest, applyLiveAgentControlRequests, type LiveAgentControlCursor } from "./live-agent-control.ts";
9
- import { subscribeLiveControlRealtime } from "./live-control-realtime.ts";
10
- import { eventToSidechainType, sidechainOutputPath, writeSidechainEntry } from "./sidechain-output.ts";
11
- import type { WorkflowStep } from "../workflows/workflow-config.ts";
12
- import { isLiveSessionRuntimeAvailable } from "./runtime-resolver.ts";
13
- import { redactSecrets } from "../utils/redaction.ts";
14
-
15
- export interface LiveSessionSpawnInput {
16
- manifest: TeamRunManifest;
17
- task: TeamTaskState;
18
- step: WorkflowStep;
19
- agent: AgentConfig;
20
- prompt: string;
21
- signal?: AbortSignal;
22
- transcriptPath?: string;
23
- onEvent?: (event: unknown) => void;
24
- onOutput?: (text: string) => void;
25
- runtimeConfig?: CrewRuntimeConfig;
26
- parentContext?: string;
27
- parentModel?: unknown;
28
- modelRegistry?: unknown;
29
- isCurrent?: () => boolean;
30
- }
31
-
32
- export interface LiveSessionRunResult {
33
- available: true;
34
- exitCode: number | null;
35
- stdout: string;
36
- stderr: string;
37
- jsonEvents: number;
38
- usage?: UsageState;
39
- error?: string;
40
- }
41
-
42
- export interface LiveSessionUnavailableResult {
43
- available: false;
44
- reason: string;
45
- }
46
-
47
- export interface LiveSessionPlannedResult {
48
- available: true;
49
- reason: string;
50
- }
51
-
52
- type LiveSessionModule = Record<string, unknown> & {
53
- createAgentSession?: (options?: Record<string, unknown>) => Promise<{ session: LiveSessionLike; modelFallbackMessage?: string }>;
54
- DefaultResourceLoader?: new (options: Record<string, unknown>) => { reload?: () => Promise<void> };
55
- SessionManager?: { inMemory?: (cwd?: string) => unknown; create?: (cwd?: string, sessionDir?: string) => unknown };
56
- SettingsManager?: { create?: (cwd?: string, agentDir?: string) => unknown };
57
- getAgentDir?: () => string;
58
- };
59
-
60
- type LiveSessionLike = {
61
- subscribe?: (listener: (event: unknown) => void) => (() => void);
62
- prompt?: (text: string, options?: Record<string, unknown>) => Promise<void>;
63
- steer?: (text: string) => Promise<void>;
64
- abort?: () => Promise<void> | void;
65
- getStats?: () => unknown;
66
- stats?: unknown;
67
- bindExtensions?: (bindings?: Record<string, unknown>) => Promise<void>;
68
- getActiveToolNames?: () => string[];
69
- setActiveToolsByName?: (names: string[]) => void;
70
- };
71
-
72
- function appendTranscript(filePath: string | undefined, event: unknown): void {
73
- if (!filePath) return;
74
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
75
- fs.appendFileSync(filePath, `${JSON.stringify(redactSecrets(event))}\n`, "utf-8");
76
- }
77
-
78
- function asRecord(value: unknown): Record<string, unknown> | undefined {
79
- return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
80
- }
81
-
82
- function textFromContent(content: unknown): string[] {
83
- if (typeof content === "string") return [content];
84
- if (!Array.isArray(content)) return [];
85
- return content.flatMap((part) => {
86
- const obj = asRecord(part);
87
- if (!obj) return [];
88
- if (obj.type === "text" && typeof obj.text === "string") return [obj.text];
89
- if (typeof obj.content === "string") return [obj.content];
90
- return [];
91
- });
92
- }
93
-
94
- function eventText(event: unknown): string[] {
95
- const obj = asRecord(event);
96
- if (!obj) return [];
97
- const text: string[] = [];
98
- if (typeof obj.text === "string") text.push(obj.text);
99
- text.push(...textFromContent(obj.content));
100
- const message = asRecord(obj.message);
101
- if (message) text.push(...textFromContent(message.content));
102
- return text.filter((entry) => entry.trim());
103
- }
104
-
105
- function finalAssistantText(event: unknown): string[] {
106
- const obj = asRecord(event);
107
- if (!obj || obj.type !== "message_end") return [];
108
- const message = asRecord(obj.message);
109
- if (message?.role !== "assistant") return [];
110
- return textFromContent(message.content);
111
- }
112
-
113
- function numberField(obj: Record<string, unknown> | undefined, keys: string[]): number | undefined {
114
- if (!obj) return undefined;
115
- for (const key of keys) {
116
- const value = obj[key];
117
- if (typeof value === "number" && Number.isFinite(value)) return value;
118
- }
119
- return undefined;
120
- }
121
-
122
- function modelFromRegistry(modelRegistry: unknown, modelId: string | undefined): unknown {
123
- if (!modelId || !modelId.includes("/")) return undefined;
124
- const registry = asRecord(modelRegistry);
125
- const find = registry?.find;
126
- if (typeof find !== "function") return undefined;
127
- const [provider, ...modelParts] = modelId.split("/");
128
- const id = modelParts.join("/");
129
- try {
130
- return find.call(modelRegistry, provider, id);
131
- } catch {
132
- return undefined;
133
- }
134
- }
135
-
136
- function liveSystemPrompt(input: LiveSessionSpawnInput): string {
137
- const memory = input.agent.memory ? buildMemoryBlock(input.agent.name, input.agent.memory, input.task.cwd, Boolean(input.agent.tools?.some((tool) => tool === "write" || tool === "edit"))) : "";
138
- return [
139
- "# pi-crew Live Subagent",
140
- `Run ID: ${input.manifest.runId}`,
141
- `Task ID: ${input.task.id}`,
142
- `Role: ${input.task.role}`,
143
- `Agent: ${input.agent.name}`,
144
- `Working directory: ${input.task.cwd}`,
145
- "",
146
- input.agent.systemPrompt || "Follow the user task exactly and report verification evidence.",
147
- memory ? `\n${memory}` : "",
148
- ].filter(Boolean).join("\n");
149
- }
150
-
151
- function filterActiveTools(session: LiveSessionLike, agent: AgentConfig): void {
152
- if (typeof session.getActiveToolNames !== "function" || typeof session.setActiveToolsByName !== "function") return;
153
- const recursiveTools = new Set(["team", "Team", "Agent", "get_subagent_result", "steer_subagent"]);
154
- const allowed = agent.tools?.length ? new Set(agent.tools) : undefined;
155
- const active = session.getActiveToolNames().filter((name) => !recursiveTools.has(name) && (!allowed || allowed.has(name)));
156
- session.setActiveToolsByName(active);
157
- }
158
-
159
- function usageFromStats(stats: unknown): UsageState | undefined {
160
- const obj = asRecord(stats);
161
- if (!obj) return undefined;
162
- const input = numberField(obj, ["input", "inputTokens", "input_tokens"]);
163
- const output = numberField(obj, ["output", "outputTokens", "output_tokens"]);
164
- const cacheRead = numberField(obj, ["cacheRead", "cache_read"]);
165
- const cacheWrite = numberField(obj, ["cacheWrite", "cache_write"]);
166
- const cost = numberField(obj, ["cost"]);
167
- const turns = numberField(obj, ["turns", "turnCount", "turn_count"]);
168
- return [input, output, cacheRead, cacheWrite, cost, turns].some((value) => value !== undefined) ? { input, output, cacheRead, cacheWrite, cost, turns } : undefined;
169
- }
170
-
171
- export async function probeLiveSessionRuntime(): Promise<LiveSessionUnavailableResult | LiveSessionPlannedResult> {
172
- const availability = await isLiveSessionRuntimeAvailable();
173
- if (!availability.available) return { available: false, reason: availability.reason ?? "Live-session runtime is unavailable." };
174
- return { available: true, reason: "Live-session SDK exports are available and pi-crew can run experimental in-process live agents when runtime.mode=live-session." };
175
- }
176
-
177
- export async function runLiveSessionTask(input: LiveSessionSpawnInput): Promise<LiveSessionRunResult> {
178
- const isCurrent = input.isCurrent ?? (() => true);
179
- if (process.env.PI_CREW_MOCK_LIVE_SESSION === "success") {
180
- const agentId = `${input.manifest.runId}:${input.task.id}`;
181
- const inherited = input.runtimeConfig?.inheritContext === true && input.parentContext ? ` with inherited context: ${input.parentContext}` : "";
182
- const event = { type: "message_end", message: { role: "assistant", content: [{ type: "text", text: `Mock live-session success for ${input.agent.name}${inherited}` }] } };
183
- const mockSession = { steer: async () => {}, prompt: async () => {}, abort: async () => {} };
184
- registerLiveAgent({ agentId, runId: input.manifest.runId, taskId: input.task.id, session: mockSession, status: "running" });
185
- appendTranscript(input.transcriptPath, event);
186
- const sidechainPath = sidechainOutputPath(input.manifest.stateRoot, input.task.id);
187
- writeSidechainEntry(sidechainPath, { agentId, type: "user", message: { role: "user", content: input.prompt }, cwd: input.task.cwd });
188
- writeSidechainEntry(sidechainPath, { agentId, type: "message", message: event, cwd: input.task.cwd });
189
- if (isCurrent()) input.onEvent?.(event);
190
- const stdout = `Mock live-session success for ${input.agent.name}${inherited}`;
191
- if (isCurrent()) input.onOutput?.(stdout);
192
- updateLiveAgentStatus(agentId, "completed");
193
- return { available: true, exitCode: 0, stdout, stderr: "", jsonEvents: 1 };
194
- }
195
- const availability = await isLiveSessionRuntimeAvailable();
196
- if (!availability.available) return { available: true, exitCode: 1, stdout: "", stderr: availability.reason ?? "Live-session runtime unavailable.", jsonEvents: 0, error: availability.reason };
197
- const mod = await import("@mariozechner/pi-coding-agent") as LiveSessionModule;
198
- if (typeof mod.createAgentSession !== "function") return { available: true, exitCode: 1, stdout: "", stderr: "createAgentSession export is unavailable.", jsonEvents: 0, error: "createAgentSession export is unavailable." };
199
- let session: LiveSessionLike | undefined;
200
- let unsubscribe: (() => void) | undefined;
201
- let unsubscribeControlRealtime: (() => void) | undefined;
202
- let controlTimer: ReturnType<typeof setInterval> | undefined;
203
- let stdout = "";
204
- let jsonEvents = 0;
205
- try {
206
- const agentDir = typeof mod.getAgentDir === "function" ? mod.getAgentDir() : undefined;
207
- let resourceLoader: unknown;
208
- if (mod.DefaultResourceLoader && agentDir) {
209
- resourceLoader = new mod.DefaultResourceLoader({
210
- cwd: input.task.cwd,
211
- agentDir,
212
- noPromptTemplates: true,
213
- noThemes: true,
214
- noContextFiles: input.runtimeConfig?.inheritContext !== true,
215
- systemPromptOverride: () => liveSystemPrompt(input),
216
- appendSystemPromptOverride: () => [],
217
- });
218
- await (resourceLoader as { reload?: () => Promise<void> }).reload?.();
219
- }
220
- const resolvedModel = modelFromRegistry(input.modelRegistry, input.agent.model) ?? input.parentModel;
221
- const created = await mod.createAgentSession({
222
- cwd: input.task.cwd,
223
- ...(agentDir ? { agentDir } : {}),
224
- ...(resourceLoader ? { resourceLoader } : {}),
225
- ...(mod.SessionManager?.inMemory ? { sessionManager: mod.SessionManager.inMemory(input.task.cwd) } : {}),
226
- ...(mod.SettingsManager?.create && agentDir ? { settingsManager: mod.SettingsManager.create(input.task.cwd, agentDir) } : {}),
227
- ...(input.modelRegistry ? { modelRegistry: input.modelRegistry } : {}),
228
- ...(resolvedModel ? { model: resolvedModel } : {}),
229
- ...(input.agent.thinking ? { thinkingLevel: input.agent.thinking } : {}),
230
- });
231
- session = created.session;
232
- filterActiveTools(session, input.agent);
233
- await session.bindExtensions?.({});
234
- const agentId = `${input.manifest.runId}:${input.task.id}`;
235
- registerLiveAgent({ agentId, runId: input.manifest.runId, taskId: input.task.id, session, status: "running" });
236
- let controlCursor: LiveAgentControlCursor = { offset: 0 };
237
- const seenControlRequestIds = new Set<string>();
238
- let controlBusy = false;
239
- const pollControl = async () => {
240
- if (!isCurrent() || controlBusy || !session) return;
241
- controlBusy = true;
242
- try {
243
- controlCursor = await applyLiveAgentControlRequests({ manifest: input.manifest, taskId: input.task.id, agentId, session, cursor: controlCursor, seenRequestIds: seenControlRequestIds });
244
- } finally {
245
- controlBusy = false;
246
- }
247
- };
248
- unsubscribeControlRealtime = subscribeLiveControlRealtime((request) => {
249
- if (!isCurrent() || request.runId !== input.manifest.runId || request.taskId !== input.task.id || !session) return;
250
- void applyLiveAgentControlRequest({ request, taskId: input.task.id, agentId, session, seenRequestIds: seenControlRequestIds });
251
- });
252
- await pollControl();
253
- controlTimer = setInterval(() => {
254
- if (isCurrent()) void pollControl();
255
- }, 500);
256
- let turnCount = 0;
257
- let softLimitReached = false;
258
- const maxTurns = input.runtimeConfig?.maxTurns;
259
- const graceTurns = input.runtimeConfig?.graceTurns ?? 5;
260
- const sidechainPath = sidechainOutputPath(input.manifest.stateRoot, input.task.id);
261
- writeSidechainEntry(sidechainPath, { agentId, type: "user", message: { role: "user", content: input.prompt }, cwd: input.task.cwd });
262
- if (typeof session.subscribe === "function") {
263
- unsubscribe = session.subscribe((event) => {
264
- if (!isCurrent()) return;
265
- jsonEvents += 1;
266
- appendTranscript(input.transcriptPath, event);
267
- const sidechainType = eventToSidechainType(event);
268
- if (sidechainType) writeSidechainEntry(sidechainPath, { agentId, type: sidechainType, message: event, cwd: input.task.cwd });
269
- const obj = asRecord(event);
270
- if (obj?.type === "turn_end") {
271
- turnCount += 1;
272
- if (maxTurns !== undefined && !softLimitReached && turnCount >= maxTurns) {
273
- softLimitReached = true;
274
- void session?.steer?.("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
275
- } else if (maxTurns !== undefined && softLimitReached && turnCount >= maxTurns + graceTurns) {
276
- void session?.abort?.();
277
- }
278
- }
279
- input.onEvent?.(event);
280
- const text = [...eventText(event), ...finalAssistantText(event)].join("\n");
281
- if (text.trim()) {
282
- stdout += `${text}\n`;
283
- input.onOutput?.(text);
284
- }
285
- });
286
- }
287
- if (input.signal) {
288
- if (input.signal.aborted) await session.abort?.();
289
- else input.signal.addEventListener("abort", () => { void session?.abort?.(); }, { once: true });
290
- }
291
- const effectivePrompt = input.runtimeConfig?.inheritContext === true && input.parentContext ? `${input.parentContext}\n\n---\n# Live Subagent Task\n${input.prompt}` : input.prompt;
292
- await session.prompt?.(effectivePrompt, { source: "api", expandPromptTemplates: false });
293
- const usage = usageFromStats(typeof session.getStats === "function" ? session.getStats() : session.stats);
294
- updateLiveAgentStatus(agentId, "completed");
295
- return { available: true, exitCode: 0, stdout: stdout.trim(), stderr: created.modelFallbackMessage ?? "", jsonEvents, usage };
296
- } catch (error) {
297
- const message = error instanceof Error ? error.message : String(error);
298
- updateLiveAgentStatus(`${input.manifest.runId}:${input.task.id}`, "failed");
299
- return { available: true, exitCode: 1, stdout: stdout.trim(), stderr: message, jsonEvents, error: message };
300
- } finally {
301
- if (controlTimer) clearInterval(controlTimer);
302
- unsubscribeControlRealtime?.();
303
- unsubscribe?.();
304
- }
305
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { AgentConfig } from "../agents/agent-config.ts";
4
+ import type { CrewRuntimeConfig } from "../config/config.ts";
5
+ import type { TeamRunManifest, TeamTaskState, UsageState } from "../state/types.ts";
6
+ import { buildMemoryBlock } from "./agent-memory.ts";
7
+ import { registerLiveAgent, updateLiveAgentStatus } from "./live-agent-manager.ts";
8
+ import { applyLiveAgentControlRequest, applyLiveAgentControlRequests, type LiveAgentControlCursor } from "./live-agent-control.ts";
9
+ import { subscribeLiveControlRealtime } from "./live-control-realtime.ts";
10
+ import { eventToSidechainType, sidechainOutputPath, writeSidechainEntry } from "./sidechain-output.ts";
11
+ import type { WorkflowStep } from "../workflows/workflow-config.ts";
12
+ import { isLiveSessionRuntimeAvailable } from "./runtime-resolver.ts";
13
+ import { redactSecrets } from "../utils/redaction.ts";
14
+
15
+ export interface LiveSessionSpawnInput {
16
+ manifest: TeamRunManifest;
17
+ task: TeamTaskState;
18
+ step: WorkflowStep;
19
+ agent: AgentConfig;
20
+ prompt: string;
21
+ signal?: AbortSignal;
22
+ transcriptPath?: string;
23
+ onEvent?: (event: unknown) => void;
24
+ onOutput?: (text: string) => void;
25
+ runtimeConfig?: CrewRuntimeConfig;
26
+ parentContext?: string;
27
+ parentModel?: unknown;
28
+ modelRegistry?: unknown;
29
+ isCurrent?: () => boolean;
30
+ }
31
+
32
+ export interface LiveSessionRunResult {
33
+ available: true;
34
+ exitCode: number | null;
35
+ stdout: string;
36
+ stderr: string;
37
+ jsonEvents: number;
38
+ usage?: UsageState;
39
+ error?: string;
40
+ }
41
+
42
+ export interface LiveSessionUnavailableResult {
43
+ available: false;
44
+ reason: string;
45
+ }
46
+
47
+ export interface LiveSessionPlannedResult {
48
+ available: true;
49
+ reason: string;
50
+ }
51
+
52
+ type LiveSessionModule = Record<string, unknown> & {
53
+ createAgentSession?: (options?: Record<string, unknown>) => Promise<{ session: LiveSessionLike; modelFallbackMessage?: string }>;
54
+ DefaultResourceLoader?: new (options: Record<string, unknown>) => { reload?: () => Promise<void> };
55
+ SessionManager?: { inMemory?: (cwd?: string) => unknown; create?: (cwd?: string, sessionDir?: string) => unknown };
56
+ SettingsManager?: { create?: (cwd?: string, agentDir?: string) => unknown };
57
+ getAgentDir?: () => string;
58
+ };
59
+
60
+ type LiveSessionLike = {
61
+ subscribe?: (listener: (event: unknown) => void) => (() => void);
62
+ prompt?: (text: string, options?: Record<string, unknown>) => Promise<void>;
63
+ steer?: (text: string) => Promise<void>;
64
+ abort?: () => Promise<void> | void;
65
+ getStats?: () => unknown;
66
+ stats?: unknown;
67
+ bindExtensions?: (bindings?: Record<string, unknown>) => Promise<void>;
68
+ getActiveToolNames?: () => string[];
69
+ setActiveToolsByName?: (names: string[]) => void;
70
+ };
71
+
72
+ function appendTranscript(filePath: string | undefined, event: unknown): void {
73
+ if (!filePath) return;
74
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
75
+ fs.appendFileSync(filePath, `${JSON.stringify(redactSecrets(event))}\n`, "utf-8");
76
+ }
77
+
78
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
79
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
80
+ }
81
+
82
+ function textFromContent(content: unknown): string[] {
83
+ if (typeof content === "string") return [content];
84
+ if (!Array.isArray(content)) return [];
85
+ return content.flatMap((part) => {
86
+ const obj = asRecord(part);
87
+ if (!obj) return [];
88
+ if (obj.type === "text" && typeof obj.text === "string") return [obj.text];
89
+ if (typeof obj.content === "string") return [obj.content];
90
+ return [];
91
+ });
92
+ }
93
+
94
+ function eventText(event: unknown): string[] {
95
+ const obj = asRecord(event);
96
+ if (!obj) return [];
97
+ const text: string[] = [];
98
+ if (typeof obj.text === "string") text.push(obj.text);
99
+ text.push(...textFromContent(obj.content));
100
+ const message = asRecord(obj.message);
101
+ if (message) text.push(...textFromContent(message.content));
102
+ return text.filter((entry) => entry.trim());
103
+ }
104
+
105
+ function finalAssistantText(event: unknown): string[] {
106
+ const obj = asRecord(event);
107
+ if (!obj || obj.type !== "message_end") return [];
108
+ const message = asRecord(obj.message);
109
+ if (message?.role !== "assistant") return [];
110
+ return textFromContent(message.content);
111
+ }
112
+
113
+ function numberField(obj: Record<string, unknown> | undefined, keys: string[]): number | undefined {
114
+ if (!obj) return undefined;
115
+ for (const key of keys) {
116
+ const value = obj[key];
117
+ if (typeof value === "number" && Number.isFinite(value)) return value;
118
+ }
119
+ return undefined;
120
+ }
121
+
122
+ function modelFromRegistry(modelRegistry: unknown, modelId: string | undefined): unknown {
123
+ if (!modelId || !modelId.includes("/")) return undefined;
124
+ const registry = asRecord(modelRegistry);
125
+ const find = registry?.find;
126
+ if (typeof find !== "function") return undefined;
127
+ const [provider, ...modelParts] = modelId.split("/");
128
+ const id = modelParts.join("/");
129
+ try {
130
+ return find.call(modelRegistry, provider, id);
131
+ } catch {
132
+ return undefined;
133
+ }
134
+ }
135
+
136
+ function liveSystemPrompt(input: LiveSessionSpawnInput): string {
137
+ const memory = input.agent.memory ? buildMemoryBlock(input.agent.name, input.agent.memory, input.task.cwd, Boolean(input.agent.tools?.some((tool) => tool === "write" || tool === "edit"))) : "";
138
+ return [
139
+ "# pi-crew Live Subagent",
140
+ `Run ID: ${input.manifest.runId}`,
141
+ `Task ID: ${input.task.id}`,
142
+ `Role: ${input.task.role}`,
143
+ `Agent: ${input.agent.name}`,
144
+ `Working directory: ${input.task.cwd}`,
145
+ "",
146
+ input.agent.systemPrompt || "Follow the user task exactly and report verification evidence.",
147
+ memory ? `\n${memory}` : "",
148
+ ].filter(Boolean).join("\n");
149
+ }
150
+
151
+ function filterActiveTools(session: LiveSessionLike, agent: AgentConfig): void {
152
+ if (typeof session.getActiveToolNames !== "function" || typeof session.setActiveToolsByName !== "function") return;
153
+ const recursiveTools = new Set(["team", "Team", "Agent", "get_subagent_result", "steer_subagent"]);
154
+ const allowed = agent.tools?.length ? new Set(agent.tools) : undefined;
155
+ const active = session.getActiveToolNames().filter((name) => !recursiveTools.has(name) && (!allowed || allowed.has(name)));
156
+ session.setActiveToolsByName(active);
157
+ }
158
+
159
+ function usageFromStats(stats: unknown): UsageState | undefined {
160
+ const obj = asRecord(stats);
161
+ if (!obj) return undefined;
162
+ const input = numberField(obj, ["input", "inputTokens", "input_tokens"]);
163
+ const output = numberField(obj, ["output", "outputTokens", "output_tokens"]);
164
+ const cacheRead = numberField(obj, ["cacheRead", "cache_read"]);
165
+ const cacheWrite = numberField(obj, ["cacheWrite", "cache_write"]);
166
+ const cost = numberField(obj, ["cost"]);
167
+ const turns = numberField(obj, ["turns", "turnCount", "turn_count"]);
168
+ return [input, output, cacheRead, cacheWrite, cost, turns].some((value) => value !== undefined) ? { input, output, cacheRead, cacheWrite, cost, turns } : undefined;
169
+ }
170
+
171
+ export async function probeLiveSessionRuntime(): Promise<LiveSessionUnavailableResult | LiveSessionPlannedResult> {
172
+ const availability = await isLiveSessionRuntimeAvailable();
173
+ if (!availability.available) return { available: false, reason: availability.reason ?? "Live-session runtime is unavailable." };
174
+ return { available: true, reason: "Live-session SDK exports are available and pi-crew can run experimental in-process live agents when runtime.mode=live-session." };
175
+ }
176
+
177
+ export async function runLiveSessionTask(input: LiveSessionSpawnInput): Promise<LiveSessionRunResult> {
178
+ const isCurrent = input.isCurrent ?? (() => true);
179
+ if (process.env.PI_CREW_MOCK_LIVE_SESSION === "success") {
180
+ const agentId = `${input.manifest.runId}:${input.task.id}`;
181
+ const inherited = input.runtimeConfig?.inheritContext === true && input.parentContext ? ` with inherited context: ${input.parentContext}` : "";
182
+ const event = { type: "message_end", message: { role: "assistant", content: [{ type: "text", text: `Mock live-session success for ${input.agent.name}${inherited}` }] } };
183
+ const mockSession = { steer: async () => {}, prompt: async () => {}, abort: async () => {} };
184
+ registerLiveAgent({ agentId, runId: input.manifest.runId, taskId: input.task.id, session: mockSession, status: "running" });
185
+ appendTranscript(input.transcriptPath, event);
186
+ const sidechainPath = sidechainOutputPath(input.manifest.stateRoot, input.task.id);
187
+ writeSidechainEntry(sidechainPath, { agentId, type: "user", message: { role: "user", content: input.prompt }, cwd: input.task.cwd });
188
+ writeSidechainEntry(sidechainPath, { agentId, type: "message", message: event, cwd: input.task.cwd });
189
+ if (isCurrent()) input.onEvent?.(event);
190
+ const stdout = `Mock live-session success for ${input.agent.name}${inherited}`;
191
+ if (isCurrent()) input.onOutput?.(stdout);
192
+ updateLiveAgentStatus(agentId, "completed");
193
+ return { available: true, exitCode: 0, stdout, stderr: "", jsonEvents: 1 };
194
+ }
195
+ const availability = await isLiveSessionRuntimeAvailable();
196
+ if (!availability.available) return { available: true, exitCode: 1, stdout: "", stderr: availability.reason ?? "Live-session runtime unavailable.", jsonEvents: 0, error: availability.reason };
197
+ const mod = await import("@mariozechner/pi-coding-agent") as LiveSessionModule;
198
+ if (typeof mod.createAgentSession !== "function") return { available: true, exitCode: 1, stdout: "", stderr: "createAgentSession export is unavailable.", jsonEvents: 0, error: "createAgentSession export is unavailable." };
199
+ let session: LiveSessionLike | undefined;
200
+ let unsubscribe: (() => void) | undefined;
201
+ let unsubscribeControlRealtime: (() => void) | undefined;
202
+ let controlTimer: ReturnType<typeof setInterval> | undefined;
203
+ let stdout = "";
204
+ let jsonEvents = 0;
205
+ try {
206
+ const agentDir = typeof mod.getAgentDir === "function" ? mod.getAgentDir() : undefined;
207
+ let resourceLoader: unknown;
208
+ if (mod.DefaultResourceLoader && agentDir) {
209
+ resourceLoader = new mod.DefaultResourceLoader({
210
+ cwd: input.task.cwd,
211
+ agentDir,
212
+ noPromptTemplates: true,
213
+ noThemes: true,
214
+ noContextFiles: input.runtimeConfig?.inheritContext !== true,
215
+ systemPromptOverride: () => liveSystemPrompt(input),
216
+ appendSystemPromptOverride: () => [],
217
+ });
218
+ await (resourceLoader as { reload?: () => Promise<void> }).reload?.();
219
+ }
220
+ const resolvedModel = modelFromRegistry(input.modelRegistry, input.agent.model) ?? input.parentModel;
221
+ const created = await mod.createAgentSession({
222
+ cwd: input.task.cwd,
223
+ ...(agentDir ? { agentDir } : {}),
224
+ ...(resourceLoader ? { resourceLoader } : {}),
225
+ ...(mod.SessionManager?.inMemory ? { sessionManager: mod.SessionManager.inMemory(input.task.cwd) } : {}),
226
+ ...(mod.SettingsManager?.create && agentDir ? { settingsManager: mod.SettingsManager.create(input.task.cwd, agentDir) } : {}),
227
+ ...(input.modelRegistry ? { modelRegistry: input.modelRegistry } : {}),
228
+ ...(resolvedModel ? { model: resolvedModel } : {}),
229
+ ...(input.agent.thinking ? { thinkingLevel: input.agent.thinking } : {}),
230
+ });
231
+ session = created.session;
232
+ filterActiveTools(session, input.agent);
233
+ await session.bindExtensions?.({});
234
+ const agentId = `${input.manifest.runId}:${input.task.id}`;
235
+ registerLiveAgent({ agentId, runId: input.manifest.runId, taskId: input.task.id, session, status: "running" });
236
+ let controlCursor: LiveAgentControlCursor = { offset: 0 };
237
+ const seenControlRequestIds = new Set<string>();
238
+ let controlBusy = false;
239
+ const pollControl = async () => {
240
+ if (!isCurrent() || controlBusy || !session) return;
241
+ controlBusy = true;
242
+ try {
243
+ controlCursor = await applyLiveAgentControlRequests({ manifest: input.manifest, taskId: input.task.id, agentId, session, cursor: controlCursor, seenRequestIds: seenControlRequestIds });
244
+ } finally {
245
+ controlBusy = false;
246
+ }
247
+ };
248
+ unsubscribeControlRealtime = subscribeLiveControlRealtime((request) => {
249
+ if (!isCurrent() || request.runId !== input.manifest.runId || request.taskId !== input.task.id || !session) return;
250
+ void applyLiveAgentControlRequest({ request, taskId: input.task.id, agentId, session, seenRequestIds: seenControlRequestIds });
251
+ });
252
+ await pollControl();
253
+ controlTimer = setInterval(() => {
254
+ if (isCurrent()) void pollControl();
255
+ }, 500);
256
+ let turnCount = 0;
257
+ let softLimitReached = false;
258
+ const maxTurns = input.runtimeConfig?.maxTurns;
259
+ const graceTurns = input.runtimeConfig?.graceTurns ?? 5;
260
+ const sidechainPath = sidechainOutputPath(input.manifest.stateRoot, input.task.id);
261
+ writeSidechainEntry(sidechainPath, { agentId, type: "user", message: { role: "user", content: input.prompt }, cwd: input.task.cwd });
262
+ if (typeof session.subscribe === "function") {
263
+ unsubscribe = session.subscribe((event) => {
264
+ if (!isCurrent()) return;
265
+ jsonEvents += 1;
266
+ appendTranscript(input.transcriptPath, event);
267
+ const sidechainType = eventToSidechainType(event);
268
+ if (sidechainType) writeSidechainEntry(sidechainPath, { agentId, type: sidechainType, message: event, cwd: input.task.cwd });
269
+ const obj = asRecord(event);
270
+ if (obj?.type === "turn_end") {
271
+ turnCount += 1;
272
+ if (maxTurns !== undefined && !softLimitReached && turnCount >= maxTurns) {
273
+ softLimitReached = true;
274
+ void session?.steer?.("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
275
+ } else if (maxTurns !== undefined && softLimitReached && turnCount >= maxTurns + graceTurns) {
276
+ void session?.abort?.();
277
+ }
278
+ }
279
+ input.onEvent?.(event);
280
+ const text = [...eventText(event), ...finalAssistantText(event)].join("\n");
281
+ if (text.trim()) {
282
+ stdout += `${text}\n`;
283
+ input.onOutput?.(text);
284
+ }
285
+ });
286
+ }
287
+ if (input.signal) {
288
+ if (input.signal.aborted) await session.abort?.();
289
+ else input.signal.addEventListener("abort", () => { void session?.abort?.(); }, { once: true });
290
+ }
291
+ const effectivePrompt = input.runtimeConfig?.inheritContext === true && input.parentContext ? `${input.parentContext}\n\n---\n# Live Subagent Task\n${input.prompt}` : input.prompt;
292
+ await session.prompt?.(effectivePrompt, { source: "api", expandPromptTemplates: false });
293
+ const usage = usageFromStats(typeof session.getStats === "function" ? session.getStats() : session.stats);
294
+ updateLiveAgentStatus(agentId, "completed");
295
+ return { available: true, exitCode: 0, stdout: stdout.trim(), stderr: created.modelFallbackMessage ?? "", jsonEvents, usage };
296
+ } catch (error) {
297
+ const message = error instanceof Error ? error.message : String(error);
298
+ updateLiveAgentStatus(`${input.manifest.runId}:${input.task.id}`, "failed");
299
+ return { available: true, exitCode: 1, stdout: stdout.trim(), stderr: message, jsonEvents, error: message };
300
+ } finally {
301
+ if (controlTimer) clearInterval(controlTimer);
302
+ unsubscribeControlRealtime?.();
303
+ unsubscribe?.();
304
+ }
305
+ }