pi-crew 0.9.11 → 0.9.13
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.
- package/CHANGELOG.md +72 -0
- package/README.md +1 -135
- package/package.json +1 -1
- package/src/extension/crew-shortcuts.ts +29 -2
- package/src/extension/knowledge-injection.ts +236 -15
- package/src/extension/registration/commands.ts +61 -34
- package/src/extension/team-tool/chain-dispatch.ts +103 -0
- package/src/extension/team-tool/chain-executor.ts +400 -0
- package/src/extension/team-tool/run.ts +9 -0
- package/src/runtime/agent-memory.ts +5 -2
- package/src/runtime/background-runner.ts +49 -0
- package/src/runtime/chain-runner.ts +47 -8
- package/src/runtime/child-pi.ts +33 -0
- package/src/runtime/handoff-manager.ts +7 -0
- package/src/runtime/live-session-runtime.ts +10 -4
- package/src/runtime/pi-json-output.ts +5 -1
- package/src/runtime/process-status.ts +7 -2
- package/src/runtime/task-output-context.ts +36 -7
- package/src/runtime/task-runner/prompt-builder.ts +5 -1
- package/src/runtime/task-runner.ts +7 -0
- package/src/schema/team-tool-schema.ts +9 -0
- package/src/ui/crew-footer.ts +3 -3
- package/src/ui/crew-select-list.ts +1 -1
- package/src/ui/dashboard-panes/agents-pane.ts +26 -4
- package/src/ui/dashboard-panes/cancellation-pane.ts +23 -0
- package/src/ui/keybinding-map.ts +7 -3
- package/src/ui/live-conversation-overlay.ts +2 -2
- package/src/ui/live-run-sidebar.ts +18 -10
- package/src/ui/overlays/help-overlay.ts +166 -0
- package/src/ui/run-dashboard.ts +210 -70
- package/src/ui/status-colors.ts +45 -0
- package/src/ui/widget/index.ts +46 -3
- package/src/ui/widget/widget-formatters.ts +22 -7
- package/src/ui/widget/widget-renderer.ts +31 -27
- package/src/utils/visual.ts +3 -1
|
@@ -260,6 +260,66 @@ async function handleHealthDashboardAction(ctx: ExtensionCommandContext, selecti
|
|
|
260
260
|
|
|
261
261
|
let depsRef: RegisterTeamCommandsDeps | undefined;
|
|
262
262
|
|
|
263
|
+
/**
|
|
264
|
+
* Open the pi-crew run dashboard overlay and run its action loop.
|
|
265
|
+
*
|
|
266
|
+
* Extracted verbatim from the `team-dashboard` command so it is reusable from
|
|
267
|
+
* a keyboard shortcut (alt+c, see crew-shortcuts.ts). Takes the base
|
|
268
|
+
* `ExtensionContext` (the shortcut handler's context) — uses only `hasUI`,
|
|
269
|
+
* `cwd`, `ui`, and `sessionManager` fields, so both `ExtensionContext` and
|
|
270
|
+
* `ExtensionCommandContext` satisfy it. Reads run caches via the module-level
|
|
271
|
+
* `depsRef` (set by `registerTeamCommands`), so it is a no-op if commands
|
|
272
|
+
* have not been registered yet. `deps` is captured into a local const so the
|
|
273
|
+
* non-undefined narrowing survives the awaited overlay call.
|
|
274
|
+
*
|
|
275
|
+
* The dashboard action helpers (handleMailboxDashboardAction, the viewers,
|
|
276
|
+
* notifyCommandResult, teamCommandContext/handleTeamTool) are declared for
|
|
277
|
+
* `ExtensionCommandContext` but only ever read base `ExtensionContext` fields
|
|
278
|
+
* (verified). The keyboard-shortcut path supplies an `ExtensionContext`, so we
|
|
279
|
+
* bridge those over-typed helpers with a single cast rather than relaxing
|
|
280
|
+
* signatures across several modules (some outside this file's scope).
|
|
281
|
+
*/
|
|
282
|
+
export async function openTeamDashboard(ctx: ExtensionContext): Promise<void> {
|
|
283
|
+
if (!ctx.hasUI) return;
|
|
284
|
+
const deps = depsRef;
|
|
285
|
+
if (!deps) return;
|
|
286
|
+
const cmdCtx = ctx as ExtensionCommandContext;
|
|
287
|
+
for (;;) {
|
|
288
|
+
// Extract sessionId for workspace-scoped filtering
|
|
289
|
+
const sessionId = cmdCtx.sessionManager?.getSessionId?.();
|
|
290
|
+
const runs = deps.getManifestCache(cmdCtx.cwd).list(50);
|
|
291
|
+
const uiConfig = loadConfig(cmdCtx.cwd).config.ui;
|
|
292
|
+
const rightPanel = (uiConfig?.dashboardPlacement ?? DEFAULT_UI.dashboardPlacement) === "right";
|
|
293
|
+
const width = rightPanel ? Math.min(90, Math.max(40, uiConfig?.dashboardWidth ?? DEFAULT_UI.dashboardWidth)) : "90%";
|
|
294
|
+
const { RunDashboard } = await ui();
|
|
295
|
+
const selection = await cmdCtx.ui.custom<RunDashboardSelection | undefined>((tui, theme, _keybindings, done) => new RunDashboard(runs, done, theme, { placement: rightPanel ? "right" : "center", showModel: uiConfig?.showModel, showTokens: uiConfig?.showTokens, showTools: uiConfig?.showTools, snapshotCache: deps.getRunSnapshotCache?.(cmdCtx.cwd), runProvider: () => deps.getManifestCache(cmdCtx.cwd).list(50), registry: deps.getMetricRegistry?.(), workspaceId: sessionId, requestRender: () => requestRenderTarget(tui) }), { overlay: true, overlayOptions: rightPanel ? { width, minWidth: 40, maxHeight: "100%", anchor: "top-right", offsetX: 0, offsetY: 0, margin: { top: 0, right: 0, bottom: 0, left: 0 } } : { width, maxHeight: "90%", anchor: "center", margin: 2 } });
|
|
296
|
+
if (!selection) return;
|
|
297
|
+
if (selection.action === "reload") continue;
|
|
298
|
+
if (selection.action === "notifications-dismiss") {
|
|
299
|
+
deps.dismissNotifications?.();
|
|
300
|
+
cmdCtx.ui.notify("pi-crew notifications dismissed.", "info");
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
if (selection.action === "mailbox-detail") {
|
|
304
|
+
await handleMailboxDashboardAction(cmdCtx, selection.runId);
|
|
305
|
+
deps.getRunSnapshotCache?.(cmdCtx.cwd).invalidate(selection.runId);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
if (selection.action === "health-recovery" || selection.action === "health-kill-stale" || selection.action === "health-diagnostic-export") {
|
|
309
|
+
await handleHealthDashboardAction(cmdCtx, selection);
|
|
310
|
+
deps.getRunSnapshotCache?.(cmdCtx.cwd).invalidate(selection.runId);
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (selection.action === "agent-transcript" && await openTranscriptViewer(cmdCtx, selection.runId)) continue;
|
|
314
|
+
if (selection.action === "agent-live" && await openLiveConversation(cmdCtx, selection.runId)) continue;
|
|
315
|
+
if (selection.action === "agent-live") { await notifyCommandResult(cmdCtx, commandText({ content: [{ type: "text", text: "No live agent found for this run." }] })); continue; }
|
|
316
|
+
const result = selection.action === "api" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-manifest" } }, teamCommandContext(cmdCtx)) : selection.action === "agents" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "agent-dashboard" } }, teamCommandContext(cmdCtx)) : selection.action === "mailbox" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-mailbox" } }, teamCommandContext(cmdCtx)) : selection.action === "agent-events" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-events", limit: 50 } }, teamCommandContext(cmdCtx)) : selection.action === "agent-output" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-output", maxBytes: 32_000 } }, teamCommandContext(cmdCtx)) : selection.action === "agent-transcript" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-transcript" } }, teamCommandContext(cmdCtx)) : // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
317
|
+
await handleTeamTool({ action: selection.action as any, runId: selection.runId }, teamCommandContext(cmdCtx));
|
|
318
|
+
await notifyCommandResult(cmdCtx, commandText(result));
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
263
323
|
export function registerTeamCommands(pi: ExtensionAPI, deps: RegisterTeamCommandsDeps): void {
|
|
264
324
|
depsRef = deps;
|
|
265
325
|
pi.registerCommand("teams", {
|
|
@@ -497,40 +557,7 @@ export function registerTeamCommands(pi: ExtensionAPI, deps: RegisterTeamCommand
|
|
|
497
557
|
} });
|
|
498
558
|
|
|
499
559
|
pi.registerCommand("team-dashboard", { description: "Open a pi-crew run dashboard overlay", handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
500
|
-
|
|
501
|
-
// Extract sessionId for workspace-scoped filtering
|
|
502
|
-
const sessionId = ctx.sessionManager?.getSessionId?.();
|
|
503
|
-
const runs = deps.getManifestCache(ctx.cwd).list(50);
|
|
504
|
-
const uiConfig = loadConfig(ctx.cwd).config.ui;
|
|
505
|
-
const rightPanel = (uiConfig?.dashboardPlacement ?? DEFAULT_UI.dashboardPlacement) === "right";
|
|
506
|
-
const width = rightPanel ? Math.min(90, Math.max(40, uiConfig?.dashboardWidth ?? DEFAULT_UI.dashboardWidth)) : "90%";
|
|
507
|
-
const { RunDashboard } = await ui();
|
|
508
|
-
const selection = await ctx.ui.custom<RunDashboardSelection | undefined>((tui, theme, _keybindings, done) => new RunDashboard(runs, done, theme, { placement: rightPanel ? "right" : "center", showModel: uiConfig?.showModel, showTokens: uiConfig?.showTokens, showTools: uiConfig?.showTools, snapshotCache: deps.getRunSnapshotCache?.(ctx.cwd), runProvider: () => deps.getManifestCache(ctx.cwd).list(50), registry: deps.getMetricRegistry?.(), workspaceId: sessionId, requestRender: () => requestRenderTarget(tui) }), { overlay: true, overlayOptions: rightPanel ? { width, minWidth: 40, maxHeight: "100%", anchor: "top-right", offsetX: 0, offsetY: 0, margin: { top: 0, right: 0, bottom: 0, left: 0 } } : { width, maxHeight: "90%", anchor: "center", margin: 2 } });
|
|
509
|
-
if (!selection) return;
|
|
510
|
-
if (selection.action === "reload") continue;
|
|
511
|
-
if (selection.action === "notifications-dismiss") {
|
|
512
|
-
deps.dismissNotifications?.();
|
|
513
|
-
ctx.ui.notify("pi-crew notifications dismissed.", "info");
|
|
514
|
-
continue;
|
|
515
|
-
}
|
|
516
|
-
if (selection.action === "mailbox-detail") {
|
|
517
|
-
await handleMailboxDashboardAction(ctx, selection.runId);
|
|
518
|
-
deps.getRunSnapshotCache?.(ctx.cwd).invalidate(selection.runId);
|
|
519
|
-
continue;
|
|
520
|
-
}
|
|
521
|
-
if (selection.action === "health-recovery" || selection.action === "health-kill-stale" || selection.action === "health-diagnostic-export") {
|
|
522
|
-
await handleHealthDashboardAction(ctx, selection);
|
|
523
|
-
deps.getRunSnapshotCache?.(ctx.cwd).invalidate(selection.runId);
|
|
524
|
-
continue;
|
|
525
|
-
}
|
|
526
|
-
if (selection.action === "agent-transcript" && await openTranscriptViewer(ctx, selection.runId)) continue;
|
|
527
|
-
if (selection.action === "agent-live" && await openLiveConversation(ctx, selection.runId)) continue;
|
|
528
|
-
if (selection.action === "agent-live") { await notifyCommandResult(ctx, commandText({ content: [{ type: "text", text: "No live agent found for this run." }] })); continue; }
|
|
529
|
-
const result = selection.action === "api" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-manifest" } }, teamCommandContext(ctx)) : selection.action === "agents" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "agent-dashboard" } }, teamCommandContext(ctx)) : selection.action === "mailbox" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-mailbox" } }, teamCommandContext(ctx)) : selection.action === "agent-events" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-events", limit: 50 } }, teamCommandContext(ctx)) : selection.action === "agent-output" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-output", maxBytes: 32_000 } }, teamCommandContext(ctx)) : selection.action === "agent-transcript" ? await handleTeamTool({ action: "api", runId: selection.runId, config: { operation: "read-agent-transcript" } }, teamCommandContext(ctx)) : // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
530
|
-
await handleTeamTool({ action: selection.action as any, runId: selection.runId }, teamCommandContext(ctx));
|
|
531
|
-
await notifyCommandResult(ctx, commandText(result));
|
|
532
|
-
return;
|
|
533
|
-
}
|
|
560
|
+
await openTeamDashboard(ctx);
|
|
534
561
|
} });
|
|
535
562
|
|
|
536
563
|
pi.registerCommand("team-mascot", { description: "Show an animated mascot splash", handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Team-tool entry point for the `chain` feature.
|
|
3
|
+
*
|
|
4
|
+
* Dispatched from `handleRun` (run.ts) via an early-return guard:
|
|
5
|
+
* if (params.chain) → handleChainRun(params, ctx, handleRun)
|
|
6
|
+
*
|
|
7
|
+
* `handleRun` is passed by reference (NOT imported) to break the
|
|
8
|
+
* run.ts ↔ chain-dispatch.ts import cycle. This file imports only
|
|
9
|
+
* chain-runner, handoff-manager, chain-executor, and the shared
|
|
10
|
+
* tool-result helpers — none of which import run.ts.
|
|
11
|
+
*
|
|
12
|
+
* @see src/extension/team-tool/chain-executor.ts (ChainTeamRunExecutor)
|
|
13
|
+
* @see src/runtime/chain-runner.ts (ChainRunner.runChain, parseChainString)
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { ChainRunner, parseChainString } from "../../runtime/chain-runner.ts";
|
|
17
|
+
import { HandoffManager } from "../../runtime/handoff-manager.ts";
|
|
18
|
+
import { ChainTeamRunExecutor, type HandleRunFn } from "./chain-executor.ts";
|
|
19
|
+
import { result, type TeamContext } from "./context.ts";
|
|
20
|
+
import type { TeamToolParamsValue } from "../../schema/team-tool-schema.ts";
|
|
21
|
+
import type { PiTeamsToolResult } from "../tool-result.ts";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Execute a chain expression (`"a -> b -> c"`). Each step runs a real team run
|
|
25
|
+
* via the injected `handleRun`, with handoff context passed forward through the
|
|
26
|
+
* goal text. Returns a multi-line summary plus structured `data` for the TUI.
|
|
27
|
+
*
|
|
28
|
+
* @param params - Must contain `chain`. `team`/`workflow`/`model` are forwarded
|
|
29
|
+
* as per-step overrides when a step does not declare its own.
|
|
30
|
+
* @param ctx - The team tool context (cwd is used to load run manifests).
|
|
31
|
+
* @param handleRun - The run.ts `handleRun` function reference (injected).
|
|
32
|
+
*/
|
|
33
|
+
export async function handleChainRun(
|
|
34
|
+
params: TeamToolParamsValue,
|
|
35
|
+
ctx: TeamContext,
|
|
36
|
+
handleRun: HandleRunFn,
|
|
37
|
+
): Promise<PiTeamsToolResult> {
|
|
38
|
+
const chainString = params.chain;
|
|
39
|
+
if (!chainString || chainString.trim().length === 0) {
|
|
40
|
+
return result("Chain expression is empty.", { action: "run", status: "error" }, true);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const spec = parseChainString(chainString);
|
|
44
|
+
if (spec.steps.length === 0) {
|
|
45
|
+
return result(
|
|
46
|
+
"Chain must contain at least one step. Use the form: \"step1 -> step2 -> step3\".",
|
|
47
|
+
{ action: "run", status: "error" },
|
|
48
|
+
true,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Construct the concrete executor with per-step overrides forwarded from the
|
|
53
|
+
// chain invocation (overridden by any step that parsed to a @team reference).
|
|
54
|
+
const executor = new ChainTeamRunExecutor({
|
|
55
|
+
handleRun,
|
|
56
|
+
ctx,
|
|
57
|
+
overrides: {
|
|
58
|
+
team: params.team,
|
|
59
|
+
workflow: params.workflow,
|
|
60
|
+
model: params.model,
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// Surface the global continueOnError from the parsed spec (e.g. --continue-on-error=true).
|
|
65
|
+
const runner = new ChainRunner(executor, new HandoffManager());
|
|
66
|
+
const chainResult = await runner.runChain(spec, {}, undefined);
|
|
67
|
+
|
|
68
|
+
// Build a readable multi-line summary.
|
|
69
|
+
const lines: string[] = [
|
|
70
|
+
`Chain ${chainResult.success ? "completed" : "ended"}: ${spec.steps.length} step(s), ${chainResult.totalHandoffs.length} handoff(s).`,
|
|
71
|
+
"",
|
|
72
|
+
];
|
|
73
|
+
for (const s of chainResult.steps) {
|
|
74
|
+
const runId = executor.stepRunIds[s.step - 1];
|
|
75
|
+
const tag =
|
|
76
|
+
s.outcome === "success" ? "✓"
|
|
77
|
+
: s.outcome === "failure" ? "✗"
|
|
78
|
+
: s.outcome === "partial" ? "≈"
|
|
79
|
+
: "⊘";
|
|
80
|
+
lines.push(
|
|
81
|
+
`${tag} Step ${s.step} [${s.name}]: ${s.outcome} (${s.duration}ms)${runId ? ` runId=${runId}` : ""}${s.error ? ` | ${s.error}` : ""}`,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
lines.push("");
|
|
85
|
+
lines.push(
|
|
86
|
+
`Total: ${chainResult.totalDuration}ms${chainResult.totalTokens !== undefined ? `, ${chainResult.totalTokens} tokens` : ""}`,
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
return result(
|
|
90
|
+
lines.join("\n"),
|
|
91
|
+
{
|
|
92
|
+
action: "run",
|
|
93
|
+
status: chainResult.success ? "ok" : "error",
|
|
94
|
+
data: {
|
|
95
|
+
chain: true,
|
|
96
|
+
steps: chainResult.steps.length,
|
|
97
|
+
totalTokens: chainResult.totalTokens,
|
|
98
|
+
runIds: executor.stepRunIds,
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
!chainResult.success,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Concrete `ChainTaskRunner` that executes each chain step as a REAL team run.
|
|
3
|
+
*
|
|
4
|
+
* This is the production wiring that makes `ChainRunner` (and Fix C's
|
|
5
|
+
* `__chainHistoryNotes`) reachable: previously `ChainRunner` had zero production
|
|
6
|
+
* callers and only existed with unit-test mock runners. Each step delegates to
|
|
7
|
+
* the existing `handleRun` (which owns config load, team/workflow discovery,
|
|
8
|
+
* worktree preconditions, manifest creation, and `executeTeamRun`), so the
|
|
9
|
+
* ~200 lines of run machinery are NOT duplicated.
|
|
10
|
+
*
|
|
11
|
+
* Context passage (the whole point of the chain feature): `enrichContextFromHandoffs`
|
|
12
|
+
* places `__chainHistory` + `__chainHistoryNotes` into `packet.context`; this
|
|
13
|
+
* executor serializes them into a `# Previous Steps in This Chain` block that is
|
|
14
|
+
* prepended to the step's goal. `handleRun` → `executeTeamRun` → worker prompt,
|
|
15
|
+
* so step N+1's worker sees step N's handoff summary and the Fix C markers.
|
|
16
|
+
*
|
|
17
|
+
* Circular-import avoidance: `handleRun` is received as an INJECTED function
|
|
18
|
+
* reference (dependency injection) rather than a static import. `run.ts` lazy-
|
|
19
|
+
* imports `chain-dispatch.ts`, which imports this file. A static import of
|
|
20
|
+
* `run.ts` here would create a `run.ts ↔ chain-executor.ts` cycle that races
|
|
21
|
+
* module-record instantiation under jiti. The DI pattern breaks the cycle.
|
|
22
|
+
*
|
|
23
|
+
* @see src/runtime/chain-runner.ts (runChain, enrichContextFromHandoffs — Fix C)
|
|
24
|
+
* @see src/extension/team-tool/run.ts (handleRun — the reused machinery)
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import type { ChainTaskRunner } from "../../runtime/chain-runner.ts";
|
|
28
|
+
import type { TaskPacket, TaskResult, Decision } from "../../runtime/handoff-manager.ts";
|
|
29
|
+
import { loadRunManifestById, createRunPaths } from "../../state/state-store.ts";
|
|
30
|
+
import { readIfSmallWithTee } from "../../runtime/task-output-context.ts";
|
|
31
|
+
import type { TeamRunManifest, TeamTaskState } from "../../state/types.ts";
|
|
32
|
+
import type { PiTeamsToolResult } from "../tool-result.ts";
|
|
33
|
+
import { textFromToolResult } from "../tool-result.ts";
|
|
34
|
+
import type { TeamToolParamsValue } from "../../schema/team-tool-schema.ts";
|
|
35
|
+
import type { TeamContext } from "./context.ts";
|
|
36
|
+
import * as fs from "node:fs";
|
|
37
|
+
import * as path from "node:path";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Signature of `handleRun`, declared locally (type-only) to break the
|
|
41
|
+
* import cycle with run.ts. Structurally identical to
|
|
42
|
+
* `(params, ctx) => Promise<PiTeamsToolResult>`.
|
|
43
|
+
*/
|
|
44
|
+
export type HandleRunFn = (
|
|
45
|
+
params: TeamToolParamsValue,
|
|
46
|
+
ctx: TeamContext,
|
|
47
|
+
) => Promise<PiTeamsToolResult>;
|
|
48
|
+
|
|
49
|
+
/** Per-step team/workflow/model overrides forwarded from the chain invocation. */
|
|
50
|
+
export interface ChainExecutorOverrides {
|
|
51
|
+
team?: string;
|
|
52
|
+
workflow?: string;
|
|
53
|
+
model?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Shape of one entry in `context.__chainHistory` produced by enrichContextFromHandoffs. */
|
|
57
|
+
interface ChainHistoryEntry {
|
|
58
|
+
step?: string;
|
|
59
|
+
outcome?: string;
|
|
60
|
+
filesCreated?: string[];
|
|
61
|
+
filesModified?: string[];
|
|
62
|
+
decisions?: Decision[];
|
|
63
|
+
nextSteps?: string[];
|
|
64
|
+
outputText?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Serialize `packet.context.__chainHistory` (+ `__chainHistoryNotes`) into a
|
|
69
|
+
* human-readable block prefixed with `# Previous Steps in This Chain`.
|
|
70
|
+
*
|
|
71
|
+
* This is the CRITICAL coupling that makes Fix C's `__chainHistoryNotes`
|
|
72
|
+
* markers visible to step N+1's worker: those markers travel as a sibling
|
|
73
|
+
* array on the context object, and only become worker-visible once formatted
|
|
74
|
+
* into the goal text here. Returns `""` when there is no history.
|
|
75
|
+
*
|
|
76
|
+
* Extracted as a pure function for unit testability (acceptance criterion 6c).
|
|
77
|
+
*/
|
|
78
|
+
export function formatChainHistory(context: Record<string, unknown>): string {
|
|
79
|
+
const history = context.__chainHistory;
|
|
80
|
+
if (!Array.isArray(history) || history.length === 0) {
|
|
81
|
+
return "";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const lines: string[] = ["# Previous Steps in This Chain", ""];
|
|
85
|
+
|
|
86
|
+
for (const raw of history) {
|
|
87
|
+
if (!raw || typeof raw !== "object") continue;
|
|
88
|
+
const entry = raw as ChainHistoryEntry;
|
|
89
|
+
const stepName = entry.step ?? "unknown";
|
|
90
|
+
const outcome = entry.outcome ?? "unknown";
|
|
91
|
+
lines.push(`## Step ${stepName}: ${outcome}`);
|
|
92
|
+
lines.push(`Files created: ${entry.filesCreated?.length ? entry.filesCreated.join(", ") : "none"}`);
|
|
93
|
+
lines.push(`Files modified: ${entry.filesModified?.length ? entry.filesModified.join(", ") : "none"}`);
|
|
94
|
+
if (entry.decisions?.length) {
|
|
95
|
+
lines.push("Decisions:");
|
|
96
|
+
for (const d of entry.decisions) {
|
|
97
|
+
const rationale = (d && typeof d === "object" && "rationale" in d) ? String(d.rationale) : "(undocumented)";
|
|
98
|
+
const decisionOutcome = (d && typeof d === "object" && "outcome" in d) ? String(d.outcome) : "";
|
|
99
|
+
lines.push(`- ${rationale}${decisionOutcome ? ` → ${decisionOutcome}` : ""}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (entry.nextSteps?.length) {
|
|
103
|
+
lines.push("Next steps:");
|
|
104
|
+
for (const ns of entry.nextSteps) lines.push(`- ${ns}`);
|
|
105
|
+
}
|
|
106
|
+
if (entry.outputText) {
|
|
107
|
+
lines.push("Output:");
|
|
108
|
+
lines.push(entry.outputText);
|
|
109
|
+
}
|
|
110
|
+
lines.push("");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Append Fix C honesty markers verbatim — these note elided/oversized history.
|
|
114
|
+
const notes = context.__chainHistoryNotes;
|
|
115
|
+
if (Array.isArray(notes)) {
|
|
116
|
+
for (const note of notes) {
|
|
117
|
+
if (typeof note === "string" && note.length > 0) lines.push(note);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return lines.join("\n").trimEnd();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Map a completed team run's manifest+tasks → a chain `TaskResult`.
|
|
126
|
+
*
|
|
127
|
+
* Outcome is derived from the manifest status, cross-checked against task
|
|
128
|
+
* statuses (a run that completed but with a failed task reads as "partial").
|
|
129
|
+
* `usage.totalTokens` sums each task's input+output tokens; `duration` from
|
|
130
|
+
* manifest timestamps; `error` is best-effort from the first failed task or
|
|
131
|
+
* the manifest summary. `filesCreated`/`filesModified` are intentionally left
|
|
132
|
+
* unset — `TeamTaskState` does not carry them, so we never fabricate them.
|
|
133
|
+
*
|
|
134
|
+
* Extracted as a pure function for unit testability (acceptance criterion 6b).
|
|
135
|
+
*/
|
|
136
|
+
export function mapRunToTaskResult(
|
|
137
|
+
manifest: TeamRunManifest,
|
|
138
|
+
tasks: TeamTaskState[],
|
|
139
|
+
): TaskResult {
|
|
140
|
+
// Determine outcome from manifest status.
|
|
141
|
+
let outcome: TaskResult["outcome"];
|
|
142
|
+
if (manifest.status === "completed") {
|
|
143
|
+
outcome = "success";
|
|
144
|
+
} else if (
|
|
145
|
+
manifest.status === "failed" ||
|
|
146
|
+
manifest.status === "blocked" ||
|
|
147
|
+
manifest.status === "cancelled"
|
|
148
|
+
) {
|
|
149
|
+
outcome = "failure";
|
|
150
|
+
} else {
|
|
151
|
+
// queued / planning / running → not terminal yet
|
|
152
|
+
outcome = "partial";
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Cross-check tasks: if a manifest claims completed but a task failed, it is partial.
|
|
156
|
+
const hasFailed = tasks.some((t) => t.status === "failed" || t.status === "needs_attention");
|
|
157
|
+
const hasCompleted = tasks.some((t) => t.status === "completed");
|
|
158
|
+
if (hasFailed && (hasCompleted || outcome === "success")) {
|
|
159
|
+
outcome = "partial";
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Token usage: sum task input + output.
|
|
163
|
+
let totalTokens = 0;
|
|
164
|
+
for (const t of tasks) {
|
|
165
|
+
totalTokens += (t.usage?.input ?? 0) + (t.usage?.output ?? 0);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Duration from manifest timestamps.
|
|
169
|
+
let duration = 0;
|
|
170
|
+
const created = Date.parse(manifest.createdAt);
|
|
171
|
+
const updated = Date.parse(manifest.updatedAt);
|
|
172
|
+
if (!Number.isNaN(created) && !Number.isNaN(updated) && updated >= created) {
|
|
173
|
+
duration = updated - created;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Error: best-effort from first failed task, else manifest summary.
|
|
177
|
+
let error: string | undefined;
|
|
178
|
+
if (outcome !== "success") {
|
|
179
|
+
const failedTask = tasks.find((t) => t.status === "failed");
|
|
180
|
+
error = failedTask?.error ?? manifest.summary;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const taskResult: TaskResult = {
|
|
184
|
+
outcome,
|
|
185
|
+
usage: { totalTokens },
|
|
186
|
+
duration,
|
|
187
|
+
};
|
|
188
|
+
if (error) taskResult.error = error;
|
|
189
|
+
return taskResult;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Read completed tasks' result artifacts and concatenate their output text.
|
|
194
|
+
* Mirrors the pattern in task-output-context.ts:collectDependencyOutputContext
|
|
195
|
+
* (readIfSmallWithTee with baseDir = artifactsRoot).
|
|
196
|
+
*
|
|
197
|
+
* Returns the concatenated output text, or undefined if no artifacts were readable.
|
|
198
|
+
*/
|
|
199
|
+
export function readChainStepOutput(
|
|
200
|
+
manifest: TeamRunManifest,
|
|
201
|
+
tasks: TeamTaskState[],
|
|
202
|
+
): string | undefined {
|
|
203
|
+
const parts: string[] = [];
|
|
204
|
+
for (const t of tasks) {
|
|
205
|
+
if (t.status !== "completed" || !t.resultArtifact?.path) continue;
|
|
206
|
+
const read = readIfSmallWithTee(t.resultArtifact.path, {
|
|
207
|
+
baseDir: manifest.artifactsRoot,
|
|
208
|
+
});
|
|
209
|
+
if (read?.content && read.content.trim().length > 0) {
|
|
210
|
+
parts.push(read.content.trim());
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return parts.length > 0 ? parts.join("\n\n") : undefined;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Concrete `ChainTaskRunner`: each step is a full team run via the injected
|
|
218
|
+
* `handleRun`. Step runIds are captured on `stepRunIds` so the dispatch can
|
|
219
|
+
* surface them in the summary and acceptance verification.
|
|
220
|
+
*
|
|
221
|
+
* Errors are intentionally NOT caught here — `runChain` wraps each step's
|
|
222
|
+
* `runTask` call in try/catch, records `outcome: "failure"`, and respects
|
|
223
|
+
* `continueOnError`. Letting exceptions propagate keeps the chain-runner's
|
|
224
|
+
* existing failure semantics intact.
|
|
225
|
+
*/
|
|
226
|
+
export class ChainTeamRunExecutor implements ChainTaskRunner {
|
|
227
|
+
/** RunId captured per executed step, in execution order. */
|
|
228
|
+
readonly stepRunIds: string[] = [];
|
|
229
|
+
|
|
230
|
+
private readonly handleRunRef: HandleRunFn;
|
|
231
|
+
private readonly ctx: TeamContext;
|
|
232
|
+
private readonly overrides: ChainExecutorOverrides;
|
|
233
|
+
|
|
234
|
+
constructor(opts: {
|
|
235
|
+
handleRun: HandleRunFn;
|
|
236
|
+
ctx: TeamContext;
|
|
237
|
+
overrides?: ChainExecutorOverrides;
|
|
238
|
+
}) {
|
|
239
|
+
this.handleRunRef = opts.handleRun;
|
|
240
|
+
this.ctx = opts.ctx;
|
|
241
|
+
this.overrides = opts.overrides ?? {};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async runTask(packet: TaskPacket): Promise<TaskResult> {
|
|
245
|
+
const context = packet.context ?? {};
|
|
246
|
+
|
|
247
|
+
// 1. Format chain history into the goal — this is how context reaches the worker.
|
|
248
|
+
// Mirrors the parentContext pattern in child-pi.ts (parent context + task delimiter).
|
|
249
|
+
const historyPrefix = formatChainHistory(context);
|
|
250
|
+
const enrichedGoal = historyPrefix
|
|
251
|
+
? `${historyPrefix}\n\n---\n# Current Chain Step\n${packet.goal}`
|
|
252
|
+
: packet.goal;
|
|
253
|
+
|
|
254
|
+
// 2. Resolve team/workflow/model: step config (set by executeStep) → overrides → default.
|
|
255
|
+
const stepTeam =
|
|
256
|
+
(context.__chainStepTeam as string | undefined) ??
|
|
257
|
+
this.overrides.team ??
|
|
258
|
+
"default";
|
|
259
|
+
const stepWorkflow =
|
|
260
|
+
(context.__chainStepWorkflow as string | undefined) ??
|
|
261
|
+
this.overrides.workflow;
|
|
262
|
+
const stepModel =
|
|
263
|
+
(context.__chainStepModel as string | undefined) ??
|
|
264
|
+
this.overrides.model;
|
|
265
|
+
|
|
266
|
+
// 3. Call handleRun for the heavy lifting. async:false forces each step to
|
|
267
|
+
// complete synchronously (overrides asyncByDefault) so the chain is sequential.
|
|
268
|
+
// NO `chain` key here — so the run.ts guard does not re-enter chain dispatch.
|
|
269
|
+
const runParams: TeamToolParamsValue = {
|
|
270
|
+
action: "run",
|
|
271
|
+
goal: enrichedGoal,
|
|
272
|
+
team: stepTeam,
|
|
273
|
+
async: false,
|
|
274
|
+
...(stepWorkflow ? { workflow: stepWorkflow } : {}),
|
|
275
|
+
...(stepModel ? { model: stepModel } : {}),
|
|
276
|
+
};
|
|
277
|
+
const runRes = await this.handleRunRef(runParams, this.ctx);
|
|
278
|
+
|
|
279
|
+
// 4. Extract runId + map to TaskResult. If no runId, the run was blocked before
|
|
280
|
+
// a manifest existed — map as a failure.
|
|
281
|
+
const runId = runRes.details?.runId;
|
|
282
|
+
if (!runId) {
|
|
283
|
+
return {
|
|
284
|
+
outcome: "failure",
|
|
285
|
+
error: textFromToolResult(runRes) || "Chain step produced no runId",
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
this.stepRunIds.push(runId);
|
|
289
|
+
|
|
290
|
+
const cwd = this.ctx.cwd ?? process.cwd();
|
|
291
|
+
const loaded = loadRunManifestById(cwd, runId);
|
|
292
|
+
if (!loaded) {
|
|
293
|
+
// Manifest not loadable — fall back to the tool result's own status.
|
|
294
|
+
return {
|
|
295
|
+
outcome: runRes.details?.status === "error" ? "failure" : "partial",
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
const result = mapRunToTaskResult(loaded.manifest, loaded.tasks);
|
|
299
|
+
const outputText = readChainStepOutput(loaded.manifest, loaded.tasks);
|
|
300
|
+
if (outputText) result.outputText = outputText;
|
|
301
|
+
return result;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ─── test helpers (exported for unit/integration tests) ──────────────────
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Write a minimal valid run fixture (manifest + tasks + events) to `cwd`'s
|
|
309
|
+
* state root so `loadRunManifestById(cwd, runId)` validates and returns it.
|
|
310
|
+
* Used by integration tests to exercise `ChainTeamRunExecutor` with a mocked
|
|
311
|
+
* `handleRun` while still going through the REAL manifest loader + result mapper.
|
|
312
|
+
*/
|
|
313
|
+
export function writeRunFixture(
|
|
314
|
+
cwd: string,
|
|
315
|
+
runId: string,
|
|
316
|
+
opts: {
|
|
317
|
+
status?: TeamRunManifest["status"];
|
|
318
|
+
tasks?: TeamTaskState[];
|
|
319
|
+
summary?: string;
|
|
320
|
+
/** Worker result text to write to results/<taskId>.txt (sets resultArtifact on tasks). */
|
|
321
|
+
resultText?: string;
|
|
322
|
+
/** Task ID for the result artifact (default: "01_task"). */
|
|
323
|
+
taskId?: string;
|
|
324
|
+
},
|
|
325
|
+
): TeamRunManifest {
|
|
326
|
+
const paths = createRunPaths(cwd, runId);
|
|
327
|
+
fs.mkdirSync(paths.stateRoot, { recursive: true });
|
|
328
|
+
const now = new Date().toISOString();
|
|
329
|
+
const start = new Date(Date.now() - 10_000).toISOString();
|
|
330
|
+
const taskId = opts.taskId ?? "01_task";
|
|
331
|
+
|
|
332
|
+
// Build tasks: if resultText is provided without explicit tasks, create a
|
|
333
|
+
// default completed task carrying a resultArtifact pointing at the result file.
|
|
334
|
+
let tasks = opts.tasks;
|
|
335
|
+
if (opts.resultText) {
|
|
336
|
+
const resultArtifact = {
|
|
337
|
+
kind: "result" as const,
|
|
338
|
+
path: `results/${taskId}.txt`,
|
|
339
|
+
createdAt: now,
|
|
340
|
+
producer: "worker",
|
|
341
|
+
retention: "run" as const,
|
|
342
|
+
};
|
|
343
|
+
if (!tasks || tasks.length === 0) {
|
|
344
|
+
tasks = [{
|
|
345
|
+
id: taskId,
|
|
346
|
+
runId,
|
|
347
|
+
role: "executor",
|
|
348
|
+
agent: "executor",
|
|
349
|
+
title: "(chain step fixture)",
|
|
350
|
+
status: "completed",
|
|
351
|
+
dependsOn: [],
|
|
352
|
+
cwd,
|
|
353
|
+
resultArtifact,
|
|
354
|
+
}];
|
|
355
|
+
} else {
|
|
356
|
+
// Attach resultArtifact to the first task if it doesn't have one.
|
|
357
|
+
tasks = tasks.map((t, i) => i === 0 && !t.resultArtifact
|
|
358
|
+
? { ...t, resultArtifact }
|
|
359
|
+
: t);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const manifest: TeamRunManifest = {
|
|
364
|
+
schemaVersion: 1,
|
|
365
|
+
runId,
|
|
366
|
+
team: "default",
|
|
367
|
+
workflow: "default",
|
|
368
|
+
goal: "(chain step fixture)",
|
|
369
|
+
status: opts.status ?? "completed",
|
|
370
|
+
workspaceMode: "single",
|
|
371
|
+
createdAt: start,
|
|
372
|
+
updatedAt: now,
|
|
373
|
+
cwd,
|
|
374
|
+
stateRoot: paths.stateRoot,
|
|
375
|
+
artifactsRoot: paths.artifactsRoot,
|
|
376
|
+
tasksPath: paths.tasksPath,
|
|
377
|
+
eventsPath: paths.eventsPath,
|
|
378
|
+
artifacts: [],
|
|
379
|
+
...(opts.summary ? { summary: opts.summary } : {}),
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
// Write the result artifact file + register on manifest if resultText provided.
|
|
383
|
+
if (opts.resultText) {
|
|
384
|
+
const resultDir = path.join(paths.artifactsRoot, "results");
|
|
385
|
+
fs.mkdirSync(resultDir, { recursive: true });
|
|
386
|
+
fs.writeFileSync(path.join(resultDir, `${taskId}.txt`), opts.resultText, "utf-8");
|
|
387
|
+
manifest.artifacts.push({
|
|
388
|
+
kind: "result",
|
|
389
|
+
path: `results/${taskId}.txt`,
|
|
390
|
+
createdAt: now,
|
|
391
|
+
producer: "worker",
|
|
392
|
+
retention: "run",
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
fs.writeFileSync(paths.manifestPath, JSON.stringify(manifest), "utf-8");
|
|
397
|
+
fs.writeFileSync(paths.tasksPath, JSON.stringify(tasks ?? []), "utf-8");
|
|
398
|
+
fs.writeFileSync(paths.eventsPath, "", "utf-8");
|
|
399
|
+
return manifest;
|
|
400
|
+
}
|
|
@@ -113,6 +113,15 @@ function scheduleBackgroundEarlyExitGuard(cwd: string, runId: string, pid: numbe
|
|
|
113
113
|
}
|
|
114
114
|
|
|
115
115
|
export async function handleRun(params: TeamToolParamsValue, ctx: TeamContext): Promise<PiTeamsToolResult> {
|
|
116
|
+
// CHAIN DISPATCH: runs before goal validation since a chain has no top-level
|
|
117
|
+
// goal. The injected handleRun reference breaks the run.ts ↔ chain-dispatch.ts
|
|
118
|
+
// import cycle; the lazy import defers the chain-executor cost until a chain is
|
|
119
|
+
// actually requested. Existing run/workflow paths below are unchanged.
|
|
120
|
+
if (params.chain) {
|
|
121
|
+
// LAZY: defer chain-dispatch import until a chain is actually requested.
|
|
122
|
+
const { handleChainRun } = await import("./chain-dispatch.ts");
|
|
123
|
+
return handleChainRun(params, ctx, handleRun);
|
|
124
|
+
}
|
|
116
125
|
const goal = params.goal ?? params.task;
|
|
117
126
|
if (!goal) return result("Run requires goal or task.", { action: "run", status: "error" }, true);
|
|
118
127
|
const intentPrefix = goal.length > 60 ? `${goal.slice(0, 57)}...` : goal;
|
|
@@ -43,10 +43,13 @@ export function ensureMemoryDir(memoryDir: string): void {
|
|
|
43
43
|
|
|
44
44
|
export function readMemoryIndex(memoryDir: string): string | undefined {
|
|
45
45
|
if (isSymlink(memoryDir)) return undefined;
|
|
46
|
-
const
|
|
46
|
+
const memPath = path.join(memoryDir, "MEMORY.md");
|
|
47
|
+
const content = safeReadMemoryFile(memPath);
|
|
47
48
|
if (content === undefined) return undefined;
|
|
48
49
|
const lines = content.split(/\r?\n/);
|
|
49
|
-
return lines.length > MAX_MEMORY_LINES
|
|
50
|
+
return lines.length > MAX_MEMORY_LINES
|
|
51
|
+
? `${lines.slice(0, MAX_MEMORY_LINES).join("\n")}\n... (truncated at 200 lines). Full file: ${memPath} — use the \`read\` tool if you need entries beyond the head.`
|
|
52
|
+
: content;
|
|
50
53
|
}
|
|
51
54
|
|
|
52
55
|
export function buildMemoryBlock(agentName: string, scope: AgentMemoryScope, cwd: string, writable: boolean): string {
|