pi-crew 0.1.43 → 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.
- package/CHANGELOG.md +27 -0
- package/agents/analyst.md +11 -11
- package/agents/critic.md +11 -11
- package/agents/executor.md +11 -11
- package/agents/explorer.md +11 -11
- package/agents/planner.md +11 -11
- package/agents/reviewer.md +11 -11
- package/agents/security-reviewer.md +11 -11
- package/agents/test-engineer.md +11 -11
- package/agents/verifier.md +11 -11
- package/agents/writer.md +11 -11
- package/docs/refactor-tasks-phase3.md +394 -394
- package/docs/refactor-tasks-phase4.md +564 -564
- package/docs/refactor-tasks-phase5.md +402 -402
- package/docs/refactor-tasks-phase6.md +662 -662
- package/docs/research-extension-examples.md +297 -297
- package/docs/research-extension-system.md +324 -324
- package/docs/research-optimization-plan.md +548 -548
- package/docs/research-phase10-distillation.md +199 -0
- package/docs/research-phase11-distillation.md +201 -0
- package/docs/research-pi-coding-agent.md +357 -357
- package/docs/research-source-pi-crew-reference.md +174 -174
- package/docs/runtime-flow.md +148 -148
- package/docs/source-runtime-refactor-map.md +83 -83
- package/index.ts +6 -6
- package/package.json +1 -1
- package/src/agents/agent-serializer.ts +34 -34
- package/src/agents/discover-agents.ts +1 -0
- package/src/config/config.ts +19 -0
- package/src/extension/cross-extension-rpc.ts +82 -82
- package/src/extension/register.ts +134 -8
- package/src/extension/registration/commands.ts +18 -2
- package/src/extension/registration/compaction-guard.ts +125 -125
- package/src/extension/registration/subagent-tools.ts +148 -148
- package/src/extension/registration/team-tool.ts +27 -8
- package/src/extension/run-bundle-schema.ts +89 -89
- package/src/extension/run-index.ts +19 -0
- package/src/extension/run-maintenance.ts +43 -43
- package/src/extension/team-tool/api.ts +1 -1
- package/src/extension/team-tool/cancel.ts +79 -4
- package/src/extension/team-tool/context.ts +2 -0
- package/src/extension/team-tool/handle-settings.ts +188 -188
- package/src/extension/team-tool/inspect.ts +41 -41
- package/src/extension/team-tool/lifecycle-actions.ts +79 -79
- package/src/extension/team-tool/plan.ts +19 -19
- package/src/extension/team-tool/respond.ts +84 -0
- package/src/extension/team-tool/run.ts +3 -2
- package/src/extension/team-tool/status.ts +7 -1
- package/src/extension/team-tool-types.ts +4 -0
- package/src/extension/team-tool.ts +2 -0
- package/src/i18n.ts +184 -184
- package/src/observability/event-to-metric.ts +6 -0
- package/src/observability/exporters/otlp-exporter.ts +77 -77
- package/src/prompt/prompt-runtime.ts +72 -72
- package/src/runtime/agent-control.ts +63 -63
- package/src/runtime/agent-memory.ts +72 -72
- package/src/runtime/agent-observability.ts +114 -114
- package/src/runtime/async-marker.ts +26 -26
- package/src/runtime/attention-events.ts +28 -28
- package/src/runtime/background-runner.ts +53 -53
- package/src/runtime/child-pi.ts +444 -444
- package/src/runtime/completion-guard.ts +87 -0
- package/src/runtime/crash-recovery.ts +30 -0
- package/src/runtime/crew-agent-records.ts +8 -0
- package/src/runtime/crew-agent-runtime.ts +2 -1
- package/src/runtime/delivery-coordinator.ts +154 -0
- package/src/runtime/direct-run.ts +35 -35
- package/src/runtime/foreground-control.ts +82 -82
- package/src/runtime/green-contract.ts +46 -46
- package/src/runtime/group-join.ts +106 -106
- package/src/runtime/heartbeat-gradient.ts +28 -28
- package/src/runtime/heartbeat-watcher.ts +124 -124
- package/src/runtime/live-agent-control.ts +87 -87
- package/src/runtime/live-agent-manager.ts +85 -85
- package/src/runtime/live-control-realtime.ts +36 -36
- package/src/runtime/live-session-runtime.ts +305 -305
- package/src/runtime/model-fallback.ts +5 -2
- package/src/runtime/overflow-recovery.ts +176 -0
- package/src/runtime/parallel-research.ts +44 -44
- package/src/runtime/pi-json-output.ts +111 -111
- package/src/runtime/policy-engine.ts +79 -79
- package/src/runtime/process-status.ts +1 -1
- package/src/runtime/progress-event-coalescer.ts +43 -43
- package/src/runtime/recovery-recipes.ts +74 -74
- package/src/runtime/retry-executor.ts +64 -64
- package/src/runtime/role-permission.ts +39 -39
- package/src/runtime/session-resources.ts +25 -0
- package/src/runtime/session-snapshot.ts +59 -0
- package/src/runtime/session-usage.ts +79 -79
- package/src/runtime/sidechain-output.ts +29 -29
- package/src/runtime/stale-reconciler.ts +199 -0
- package/src/runtime/supervisor-contact.ts +59 -0
- package/src/runtime/task-display.ts +38 -38
- package/src/runtime/task-output-context.ts +127 -127
- package/src/runtime/task-runner/live-executor.ts +101 -101
- package/src/runtime/task-runner/progress.ts +119 -119
- package/src/runtime/task-runner/result-utils.ts +14 -14
- package/src/runtime/task-runner/state-helpers.ts +22 -22
- package/src/runtime/task-runner.ts +14 -0
- package/src/runtime/team-runner.ts +19 -8
- package/src/runtime/worker-heartbeat.ts +21 -21
- package/src/runtime/worker-startup.ts +57 -57
- package/src/schema/config-schema.ts +1 -0
- package/src/schema/team-tool-schema.ts +6 -1
- package/src/state/contracts.ts +6 -2
- package/src/state/state-store.ts +43 -0
- package/src/state/task-claims.ts +44 -44
- package/src/state/types.ts +2 -0
- package/src/state/usage.ts +29 -29
- package/src/subagents/async-entry.ts +1 -1
- package/src/subagents/index.ts +3 -3
- package/src/subagents/live/control.ts +1 -1
- package/src/subagents/live/manager.ts +1 -1
- package/src/subagents/live/realtime.ts +1 -1
- package/src/subagents/live/session-runtime.ts +1 -1
- package/src/subagents/manager.ts +1 -1
- package/src/subagents/spawn.ts +1 -1
- package/src/teams/team-serializer.ts +38 -38
- package/src/types/diff.d.ts +18 -18
- package/src/ui/crew-footer.ts +101 -101
- package/src/ui/crew-select-list.ts +111 -111
- package/src/ui/crew-widget.ts +10 -5
- package/src/ui/dashboard-panes/mailbox-pane.ts +2 -1
- package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
- package/src/ui/dynamic-border.ts +25 -25
- package/src/ui/layout-primitives.ts +106 -106
- package/src/ui/loaders.ts +158 -158
- package/src/ui/powerbar-publisher.ts +4 -4
- package/src/ui/render-diff.ts +119 -119
- package/src/ui/render-scheduler.ts +143 -143
- package/src/ui/run-snapshot-cache.ts +310 -17
- package/src/ui/snapshot-types.ts +5 -0
- package/src/ui/spinner.ts +17 -17
- package/src/ui/status-colors.ts +58 -54
- package/src/ui/syntax-highlight.ts +116 -116
- package/src/utils/atomic-write.ts +33 -0
- package/src/utils/completion-dedupe.ts +63 -63
- package/src/utils/frontmatter.ts +68 -68
- package/src/utils/git.ts +262 -262
- package/src/utils/ids.ts +12 -12
- package/src/utils/names.ts +27 -27
- package/src/utils/redaction.ts +44 -44
- package/src/utils/safe-paths.ts +47 -47
- package/src/utils/sleep.ts +32 -32
- package/src/workflows/validate-workflow.ts +40 -40
- package/src/worktree/branch-freshness.ts +45 -45
- package/teams/default.team.md +12 -12
- package/teams/fast-fix.team.md +11 -11
- package/teams/implementation.team.md +18 -18
- package/teams/parallel-research.team.md +14 -14
- package/teams/research.team.md +11 -11
- package/teams/review.team.md +12 -12
- package/workflows/default.workflow.md +29 -29
- package/workflows/fast-fix.workflow.md +22 -22
- package/workflows/implementation.workflow.md +38 -38
- package/workflows/parallel-research.workflow.md +46 -46
- package/workflows/research.workflow.md +22 -22
- package/workflows/review.workflow.md +30 -30
|
@@ -1,119 +1,119 @@
|
|
|
1
|
-
import type { UsageState } from "../../state/types.ts";
|
|
2
|
-
import type { CrewAgentProgress } from "../crew-agent-runtime.ts";
|
|
3
|
-
import { emptyCrewAgentProgress } from "../crew-agent-records.ts";
|
|
4
|
-
import type { ProgressEventSummary } from "../progress-event-coalescer.ts";
|
|
5
|
-
import type { TeamTaskState } from "../../state/types.ts";
|
|
6
|
-
|
|
7
|
-
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
8
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
function safeNum(v: number | undefined): number {
|
|
12
|
-
return Number.isFinite(v) ? v! : 0;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
function textFromContent(content: unknown): string[] {
|
|
16
|
-
if (typeof content === "string") return [content];
|
|
17
|
-
if (!Array.isArray(content)) return [];
|
|
18
|
-
const text: string[] = [];
|
|
19
|
-
for (const part of content) {
|
|
20
|
-
const obj = asRecord(part);
|
|
21
|
-
if (!obj) continue;
|
|
22
|
-
if (obj.type === "text" && typeof obj.text === "string") text.push(obj.text);
|
|
23
|
-
else if (typeof obj.content === "string") text.push(obj.content);
|
|
24
|
-
}
|
|
25
|
-
return text;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function eventText(event: unknown): string[] {
|
|
29
|
-
const obj = asRecord(event);
|
|
30
|
-
if (!obj) return [];
|
|
31
|
-
const text: string[] = [];
|
|
32
|
-
if (typeof obj.text === "string") text.push(obj.text);
|
|
33
|
-
if (typeof obj.output === "string") text.push(obj.output);
|
|
34
|
-
text.push(...textFromContent(obj.content));
|
|
35
|
-
const message = asRecord(obj.message);
|
|
36
|
-
if (message) text.push(...textFromContent(message.content));
|
|
37
|
-
return text.filter((entry) => entry.trim());
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function numberField(obj: Record<string, unknown>, keys: string[]): number | undefined {
|
|
41
|
-
for (const key of keys) {
|
|
42
|
-
const value = obj[key];
|
|
43
|
-
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
44
|
-
}
|
|
45
|
-
return undefined;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function eventUsage(event: unknown): { input?: number; output?: number; turns?: number } | undefined {
|
|
49
|
-
const obj = asRecord(event);
|
|
50
|
-
if (!obj) return undefined;
|
|
51
|
-
const direct = { input: numberField(obj, ["input", "inputTokens", "input_tokens"]), output: numberField(obj, ["output", "outputTokens", "output_tokens"]), turns: numberField(obj, ["turns", "turnCount", "turn_count"]) };
|
|
52
|
-
if (Object.values(direct).some((value) => value !== undefined)) return direct;
|
|
53
|
-
for (const key of ["usage", "tokenUsage", "tokens", "stats"]) {
|
|
54
|
-
const nested = eventUsage(obj[key]);
|
|
55
|
-
if (nested) return nested;
|
|
56
|
-
}
|
|
57
|
-
const message = asRecord(obj.message);
|
|
58
|
-
return message ? eventUsage(message.usage) : undefined;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function previewArgs(args: unknown): string | undefined {
|
|
62
|
-
if (!args) return undefined;
|
|
63
|
-
try {
|
|
64
|
-
const text = typeof args === "string" ? args : JSON.stringify(args);
|
|
65
|
-
return text.length > 240 ? `${text.slice(0, 240)}…` : text;
|
|
66
|
-
} catch {
|
|
67
|
-
return undefined;
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export function applyUsageToProgress(progress: CrewAgentProgress | undefined, usage: UsageState | undefined): CrewAgentProgress | undefined {
|
|
72
|
-
if (!usage) return progress;
|
|
73
|
-
const base = progress ?? emptyCrewAgentProgress();
|
|
74
|
-
const tokens = safeNum(usage.input) + safeNum(usage.output) + safeNum(usage.cacheRead) + safeNum(usage.cacheWrite);
|
|
75
|
-
return { ...base, tokens, turns: usage.turns ?? base.turns };
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export function shouldFlushProgressEvent(event: unknown): boolean {
|
|
79
|
-
const type = asRecord(event)?.type;
|
|
80
|
-
return type === "tool_execution_start" || type === "tool_execution_end" || type === "message_end" || type === "tool_result_end";
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function progressEventSummary(task: TeamTaskState, event: unknown): ProgressEventSummary {
|
|
84
|
-
const type = asRecord(event)?.type;
|
|
85
|
-
return { eventType: typeof type === "string" ? type : "event", currentTool: task.agentProgress?.currentTool, toolCount: task.agentProgress?.toolCount, tokens: task.agentProgress?.tokens, turns: task.agentProgress?.turns, activityState: task.agentProgress?.activityState, lastActivityAt: task.agentProgress?.lastActivityAt };
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
export function applyAgentProgressEvent(progress: CrewAgentProgress, event: unknown, startedAt: string | undefined): CrewAgentProgress {
|
|
89
|
-
const obj = asRecord(event);
|
|
90
|
-
const now = new Date().toISOString();
|
|
91
|
-
const next: CrewAgentProgress = { ...progress, recentTools: [...progress.recentTools], recentOutput: [...progress.recentOutput], lastActivityAt: now, activityState: "active" };
|
|
92
|
-
if (startedAt) {
|
|
93
|
-
const startMs = new Date(startedAt).getTime();
|
|
94
|
-
next.durationMs = Number.isFinite(startMs) ? Date.now() - startMs : undefined;
|
|
95
|
-
}
|
|
96
|
-
if (obj?.type === "tool_execution_start") {
|
|
97
|
-
next.toolCount += 1;
|
|
98
|
-
next.currentTool = typeof obj.toolName === "string" ? obj.toolName : typeof obj.name === "string" ? obj.name : "tool";
|
|
99
|
-
next.currentToolArgs = previewArgs(obj.args);
|
|
100
|
-
next.currentToolStartedAt = now;
|
|
101
|
-
}
|
|
102
|
-
if (obj?.type === "tool_execution_end") {
|
|
103
|
-
if (next.currentTool) next.recentTools.push({ tool: next.currentTool, args: next.currentToolArgs, endedAt: now });
|
|
104
|
-
next.currentTool = undefined;
|
|
105
|
-
next.currentToolArgs = undefined;
|
|
106
|
-
next.currentToolStartedAt = undefined;
|
|
107
|
-
}
|
|
108
|
-
if ((obj?.type === "tool_execution_error" || obj?.type === "tool_execution_failed") && next.currentTool) next.failedTool = next.currentTool;
|
|
109
|
-
const usage = eventUsage(event);
|
|
110
|
-
if (usage) {
|
|
111
|
-
next.tokens = safeNum(usage.input) + safeNum(usage.output);
|
|
112
|
-
next.turns = usage.turns ?? next.turns;
|
|
113
|
-
}
|
|
114
|
-
const text = eventText(event);
|
|
115
|
-
if (text.length > 0) next.recentOutput.push(...text.flatMap((entry) => entry.split(/\r?\n/)).filter(Boolean).slice(-10));
|
|
116
|
-
if (next.recentTools.length > 25) next.recentTools.splice(0, next.recentTools.length - 25);
|
|
117
|
-
if (next.recentOutput.length > 50) next.recentOutput.splice(0, next.recentOutput.length - 50);
|
|
118
|
-
return next;
|
|
119
|
-
}
|
|
1
|
+
import type { UsageState } from "../../state/types.ts";
|
|
2
|
+
import type { CrewAgentProgress } from "../crew-agent-runtime.ts";
|
|
3
|
+
import { emptyCrewAgentProgress } from "../crew-agent-records.ts";
|
|
4
|
+
import type { ProgressEventSummary } from "../progress-event-coalescer.ts";
|
|
5
|
+
import type { TeamTaskState } from "../../state/types.ts";
|
|
6
|
+
|
|
7
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
8
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function safeNum(v: number | undefined): number {
|
|
12
|
+
return Number.isFinite(v) ? v! : 0;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function textFromContent(content: unknown): string[] {
|
|
16
|
+
if (typeof content === "string") return [content];
|
|
17
|
+
if (!Array.isArray(content)) return [];
|
|
18
|
+
const text: string[] = [];
|
|
19
|
+
for (const part of content) {
|
|
20
|
+
const obj = asRecord(part);
|
|
21
|
+
if (!obj) continue;
|
|
22
|
+
if (obj.type === "text" && typeof obj.text === "string") text.push(obj.text);
|
|
23
|
+
else if (typeof obj.content === "string") text.push(obj.content);
|
|
24
|
+
}
|
|
25
|
+
return text;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function eventText(event: unknown): string[] {
|
|
29
|
+
const obj = asRecord(event);
|
|
30
|
+
if (!obj) return [];
|
|
31
|
+
const text: string[] = [];
|
|
32
|
+
if (typeof obj.text === "string") text.push(obj.text);
|
|
33
|
+
if (typeof obj.output === "string") text.push(obj.output);
|
|
34
|
+
text.push(...textFromContent(obj.content));
|
|
35
|
+
const message = asRecord(obj.message);
|
|
36
|
+
if (message) text.push(...textFromContent(message.content));
|
|
37
|
+
return text.filter((entry) => entry.trim());
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function numberField(obj: Record<string, unknown>, keys: string[]): number | undefined {
|
|
41
|
+
for (const key of keys) {
|
|
42
|
+
const value = obj[key];
|
|
43
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function eventUsage(event: unknown): { input?: number; output?: number; turns?: number } | undefined {
|
|
49
|
+
const obj = asRecord(event);
|
|
50
|
+
if (!obj) return undefined;
|
|
51
|
+
const direct = { input: numberField(obj, ["input", "inputTokens", "input_tokens"]), output: numberField(obj, ["output", "outputTokens", "output_tokens"]), turns: numberField(obj, ["turns", "turnCount", "turn_count"]) };
|
|
52
|
+
if (Object.values(direct).some((value) => value !== undefined)) return direct;
|
|
53
|
+
for (const key of ["usage", "tokenUsage", "tokens", "stats"]) {
|
|
54
|
+
const nested = eventUsage(obj[key]);
|
|
55
|
+
if (nested) return nested;
|
|
56
|
+
}
|
|
57
|
+
const message = asRecord(obj.message);
|
|
58
|
+
return message ? eventUsage(message.usage) : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function previewArgs(args: unknown): string | undefined {
|
|
62
|
+
if (!args) return undefined;
|
|
63
|
+
try {
|
|
64
|
+
const text = typeof args === "string" ? args : JSON.stringify(args);
|
|
65
|
+
return text.length > 240 ? `${text.slice(0, 240)}…` : text;
|
|
66
|
+
} catch {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function applyUsageToProgress(progress: CrewAgentProgress | undefined, usage: UsageState | undefined): CrewAgentProgress | undefined {
|
|
72
|
+
if (!usage) return progress;
|
|
73
|
+
const base = progress ?? emptyCrewAgentProgress();
|
|
74
|
+
const tokens = safeNum(usage.input) + safeNum(usage.output) + safeNum(usage.cacheRead) + safeNum(usage.cacheWrite);
|
|
75
|
+
return { ...base, tokens, turns: usage.turns ?? base.turns };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function shouldFlushProgressEvent(event: unknown): boolean {
|
|
79
|
+
const type = asRecord(event)?.type;
|
|
80
|
+
return type === "tool_execution_start" || type === "tool_execution_end" || type === "message_end" || type === "tool_result_end";
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function progressEventSummary(task: TeamTaskState, event: unknown): ProgressEventSummary {
|
|
84
|
+
const type = asRecord(event)?.type;
|
|
85
|
+
return { eventType: typeof type === "string" ? type : "event", currentTool: task.agentProgress?.currentTool, toolCount: task.agentProgress?.toolCount, tokens: task.agentProgress?.tokens, turns: task.agentProgress?.turns, activityState: task.agentProgress?.activityState, lastActivityAt: task.agentProgress?.lastActivityAt };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function applyAgentProgressEvent(progress: CrewAgentProgress, event: unknown, startedAt: string | undefined): CrewAgentProgress {
|
|
89
|
+
const obj = asRecord(event);
|
|
90
|
+
const now = new Date().toISOString();
|
|
91
|
+
const next: CrewAgentProgress = { ...progress, recentTools: [...progress.recentTools], recentOutput: [...progress.recentOutput], lastActivityAt: now, activityState: "active" };
|
|
92
|
+
if (startedAt) {
|
|
93
|
+
const startMs = new Date(startedAt).getTime();
|
|
94
|
+
next.durationMs = Number.isFinite(startMs) ? Date.now() - startMs : undefined;
|
|
95
|
+
}
|
|
96
|
+
if (obj?.type === "tool_execution_start") {
|
|
97
|
+
next.toolCount += 1;
|
|
98
|
+
next.currentTool = typeof obj.toolName === "string" ? obj.toolName : typeof obj.name === "string" ? obj.name : "tool";
|
|
99
|
+
next.currentToolArgs = previewArgs(obj.args);
|
|
100
|
+
next.currentToolStartedAt = now;
|
|
101
|
+
}
|
|
102
|
+
if (obj?.type === "tool_execution_end") {
|
|
103
|
+
if (next.currentTool) next.recentTools.push({ tool: next.currentTool, args: next.currentToolArgs, endedAt: now });
|
|
104
|
+
next.currentTool = undefined;
|
|
105
|
+
next.currentToolArgs = undefined;
|
|
106
|
+
next.currentToolStartedAt = undefined;
|
|
107
|
+
}
|
|
108
|
+
if ((obj?.type === "tool_execution_error" || obj?.type === "tool_execution_failed") && next.currentTool) next.failedTool = next.currentTool;
|
|
109
|
+
const usage = eventUsage(event);
|
|
110
|
+
if (usage) {
|
|
111
|
+
next.tokens = safeNum(usage.input) + safeNum(usage.output);
|
|
112
|
+
next.turns = usage.turns ?? next.turns;
|
|
113
|
+
}
|
|
114
|
+
const text = eventText(event);
|
|
115
|
+
if (text.length > 0) next.recentOutput.push(...text.flatMap((entry) => entry.split(/\r?\n/)).filter(Boolean).slice(-10));
|
|
116
|
+
if (next.recentTools.length > 25) next.recentTools.splice(0, next.recentTools.length - 25);
|
|
117
|
+
if (next.recentOutput.length > 50) next.recentOutput.splice(0, next.recentOutput.length - 50);
|
|
118
|
+
return next;
|
|
119
|
+
}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
export function cleanResultText(text: string | undefined): string | undefined {
|
|
2
|
-
const trimmed = text?.trim();
|
|
3
|
-
if (!trimmed) return undefined;
|
|
4
|
-
const doneIndex = trimmed.lastIndexOf("\nDONE\n");
|
|
5
|
-
if (doneIndex >= 0) return trimmed.slice(doneIndex + 1).trim();
|
|
6
|
-
if (trimmed === "DONE" || trimmed.startsWith("DONE\n")) return trimmed;
|
|
7
|
-
const fencedPromptIndex = trimmed.lastIndexOf("</file>");
|
|
8
|
-
if (fencedPromptIndex >= 0 && fencedPromptIndex < trimmed.length - 7) return trimmed.slice(fencedPromptIndex + 7).trim() || trimmed;
|
|
9
|
-
return trimmed;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function isFinalChildEvent(event: unknown): boolean {
|
|
13
|
-
return Boolean(event && typeof event === "object" && !Array.isArray(event) && (event as Record<string, unknown>).type === "message_end");
|
|
14
|
-
}
|
|
1
|
+
export function cleanResultText(text: string | undefined): string | undefined {
|
|
2
|
+
const trimmed = text?.trim();
|
|
3
|
+
if (!trimmed) return undefined;
|
|
4
|
+
const doneIndex = trimmed.lastIndexOf("\nDONE\n");
|
|
5
|
+
if (doneIndex >= 0) return trimmed.slice(doneIndex + 1).trim();
|
|
6
|
+
if (trimmed === "DONE" || trimmed.startsWith("DONE\n")) return trimmed;
|
|
7
|
+
const fencedPromptIndex = trimmed.lastIndexOf("</file>");
|
|
8
|
+
if (fencedPromptIndex >= 0 && fencedPromptIndex < trimmed.length - 7) return trimmed.slice(fencedPromptIndex + 7).trim() || trimmed;
|
|
9
|
+
return trimmed;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function isFinalChildEvent(event: unknown): boolean {
|
|
13
|
+
return Boolean(event && typeof event === "object" && !Array.isArray(event) && (event as Record<string, unknown>).type === "message_end");
|
|
14
|
+
}
|
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import type { TaskCheckpointState, TeamRunManifest, TeamTaskState } from "../../state/types.ts";
|
|
2
|
-
import { loadRunManifestById, saveRunTasks } from "../../state/state-store.ts";
|
|
3
|
-
import { recordFromTask, upsertCrewAgent } from "../crew-agent-records.ts";
|
|
4
|
-
|
|
5
|
-
export function updateTask(tasks: TeamTaskState[], updated: TeamTaskState): TeamTaskState[] {
|
|
6
|
-
return tasks.map((task) => task.id === updated.id ? updated : task);
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export function persistSingleTaskUpdate(manifest: TeamRunManifest, fallbackTasks: TeamTaskState[], updated: TeamTaskState): TeamTaskState[] {
|
|
10
|
-
const latest = loadRunManifestById(manifest.cwd, manifest.runId)?.tasks ?? fallbackTasks;
|
|
11
|
-
const merged = updateTask(latest, updated);
|
|
12
|
-
saveRunTasks(manifest, merged);
|
|
13
|
-
return merged;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function checkpointTask(manifest: TeamRunManifest, tasks: TeamTaskState[], task: TeamTaskState, phase: TaskCheckpointState["phase"], childPid?: number): { task: TeamTaskState; tasks: TeamTaskState[] } {
|
|
17
|
-
const checkpoint: TaskCheckpointState = { phase, updatedAt: new Date().toISOString(), ...(childPid ? { childPid } : task.checkpoint?.childPid ? { childPid: task.checkpoint.childPid } : {}) };
|
|
18
|
-
const nextTask = { ...task, checkpoint };
|
|
19
|
-
const nextTasks = persistSingleTaskUpdate(manifest, updateTask(tasks, nextTask), nextTask);
|
|
20
|
-
upsertCrewAgent(manifest, recordFromTask(manifest, nextTask, "child-process"));
|
|
21
|
-
return { task: nextTask, tasks: nextTasks };
|
|
22
|
-
}
|
|
1
|
+
import type { TaskCheckpointState, TeamRunManifest, TeamTaskState } from "../../state/types.ts";
|
|
2
|
+
import { loadRunManifestById, saveRunTasks } from "../../state/state-store.ts";
|
|
3
|
+
import { recordFromTask, upsertCrewAgent } from "../crew-agent-records.ts";
|
|
4
|
+
|
|
5
|
+
export function updateTask(tasks: TeamTaskState[], updated: TeamTaskState): TeamTaskState[] {
|
|
6
|
+
return tasks.map((task) => task.id === updated.id ? updated : task);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function persistSingleTaskUpdate(manifest: TeamRunManifest, fallbackTasks: TeamTaskState[], updated: TeamTaskState): TeamTaskState[] {
|
|
10
|
+
const latest = loadRunManifestById(manifest.cwd, manifest.runId)?.tasks ?? fallbackTasks;
|
|
11
|
+
const merged = updateTask(latest, updated);
|
|
12
|
+
saveRunTasks(manifest, merged);
|
|
13
|
+
return merged;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function checkpointTask(manifest: TeamRunManifest, tasks: TeamTaskState[], task: TeamTaskState, phase: TaskCheckpointState["phase"], childPid?: number): { task: TeamTaskState; tasks: TeamTaskState[] } {
|
|
17
|
+
const checkpoint: TaskCheckpointState = { phase, updatedAt: new Date().toISOString(), ...(childPid ? { childPid } : task.checkpoint?.childPid ? { childPid: task.checkpoint.childPid } : {}) };
|
|
18
|
+
const nextTask = { ...task, checkpoint };
|
|
19
|
+
const nextTasks = persistSingleTaskUpdate(manifest, updateTask(tasks, nextTask), nextTask);
|
|
20
|
+
upsertCrewAgent(manifest, recordFromTask(manifest, nextTask, "child-process"));
|
|
21
|
+
return { task: nextTask, tasks: nextTasks };
|
|
22
|
+
}
|
|
@@ -27,6 +27,7 @@ import { checkpointTask, persistSingleTaskUpdate, updateTask } from "./task-runn
|
|
|
27
27
|
import { cleanResultText, isFinalChildEvent } from "./task-runner/result-utils.ts";
|
|
28
28
|
import { evaluateCompletionMutationGuard } from "./completion-guard.ts";
|
|
29
29
|
import { appendTaskAttentionEvent } from "./attention-events.ts";
|
|
30
|
+
import { parseSupervisorContactFromLine, recordSupervisorContact } from "./supervisor-contact.ts";
|
|
30
31
|
|
|
31
32
|
export interface TaskRunnerInput {
|
|
32
33
|
manifest: TeamRunManifest;
|
|
@@ -44,6 +45,8 @@ export interface TaskRunnerInput {
|
|
|
44
45
|
modelOverride?: string;
|
|
45
46
|
limits?: CrewLimitsConfig;
|
|
46
47
|
dependencyContextText?: string;
|
|
48
|
+
/** Optional callback for JSON events from child Pi. Used for overflow recovery tracking. */
|
|
49
|
+
onJsonEvent?: (taskId: string, runId: string, event: unknown) => void;
|
|
47
50
|
}
|
|
48
51
|
|
|
49
52
|
export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: TeamRunManifest; tasks: TeamTaskState[] }> {
|
|
@@ -154,12 +157,23 @@ export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: T
|
|
|
154
157
|
onStdoutLine: (line) => {
|
|
155
158
|
appendCrewAgentOutput(manifest, task.id, line);
|
|
156
159
|
persistHeartbeat();
|
|
160
|
+
// Check for supervisor contact requests from child Pi
|
|
161
|
+
const contact = parseSupervisorContactFromLine(line);
|
|
162
|
+
if (contact) {
|
|
163
|
+
recordSupervisorContact(manifest, { runId: manifest.runId, ...contact });
|
|
164
|
+
}
|
|
157
165
|
},
|
|
158
166
|
onJsonEvent: (event) => {
|
|
159
167
|
appendCrewAgentEvent(manifest, task.id, event);
|
|
160
168
|
persistHeartbeat();
|
|
161
169
|
task = { ...task, agentProgress: applyAgentProgressEvent(task.agentProgress ?? emptyCrewAgentProgress(), event, task.startedAt) };
|
|
162
170
|
tasks = updateTask(tasks, task);
|
|
171
|
+
// Feed overflow recovery tracker
|
|
172
|
+
if (input.onJsonEvent) {
|
|
173
|
+
try {
|
|
174
|
+
input.onJsonEvent(task.id, manifest.runId, event);
|
|
175
|
+
} catch { /* overflow tracking errors should not affect task */ }
|
|
176
|
+
}
|
|
163
177
|
if (!finalCheckpointWritten && isFinalChildEvent(event)) {
|
|
164
178
|
finalCheckpointWritten = true;
|
|
165
179
|
({ task, tasks } = checkpointTask(manifest, tasks, task, "child-stdout-final"));
|
|
@@ -6,7 +6,7 @@ import { writeArtifact } from "../state/artifact-store.ts";
|
|
|
6
6
|
import { appendEvent } from "../state/event-log.ts";
|
|
7
7
|
import type { TeamConfig } from "../teams/team-config.ts";
|
|
8
8
|
import type { ArtifactDescriptor, PolicyDecision, TeamRunManifest, TaskAttemptState, TeamTaskState } from "../state/types.ts";
|
|
9
|
-
import { saveRunManifest, saveRunManifestAsync, saveRunTasksAsync, updateRunStatus } from "../state/state-store.ts";
|
|
9
|
+
import { loadRunManifestById, saveRunManifest, saveRunManifestAsync, saveRunTasksAsync, updateRunStatus } from "../state/state-store.ts";
|
|
10
10
|
import { aggregateUsage, formatUsage } from "../state/usage.ts";
|
|
11
11
|
import type { WorkflowConfig, WorkflowStep } from "../workflows/workflow-config.ts";
|
|
12
12
|
import { evaluateCrewPolicy, summarizePolicyDecisions } from "./policy-engine.ts";
|
|
@@ -43,6 +43,8 @@ export interface ExecuteTeamRunInput {
|
|
|
43
43
|
signal?: AbortSignal;
|
|
44
44
|
reliability?: CrewReliabilityConfig;
|
|
45
45
|
metricRegistry?: MetricRegistry;
|
|
46
|
+
/** Optional callback for JSON events from child Pi. Used for overflow recovery tracking. */
|
|
47
|
+
onJsonEvent?: (taskId: string, runId: string, event: unknown) => void;
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
function findStep(workflow: WorkflowConfig, task: TeamTaskState): WorkflowStep {
|
|
@@ -68,7 +70,7 @@ function mergeArtifacts(items: ArtifactDescriptor[]): ArtifactDescriptor[] {
|
|
|
68
70
|
}
|
|
69
71
|
|
|
70
72
|
function isNonTerminalTaskStatus(status: TeamTaskState["status"]): boolean {
|
|
71
|
-
return status === "queued" || status === "running";
|
|
73
|
+
return status === "queued" || status === "running" || status === "waiting";
|
|
72
74
|
}
|
|
73
75
|
|
|
74
76
|
function shouldMergeTaskUpdate(current: TeamTaskState, updated: TeamTaskState): boolean {
|
|
@@ -483,7 +485,7 @@ function ensurePlanApprovalRequested(manifest: TeamRunManifest, tasks: TeamTaskS
|
|
|
483
485
|
}
|
|
484
486
|
|
|
485
487
|
function cancelPlanTasks(tasks: TeamTaskState[], reason: string): TeamTaskState[] {
|
|
486
|
-
return tasks.map((task) => task.status === "queued" || task.status === "running" ? { ...task, status: "cancelled", finishedAt: new Date().toISOString(), error: reason, graph: task.graph ? { ...task.graph, queue: "done" } : undefined } : task);
|
|
488
|
+
return tasks.map((task) => task.status === "queued" || task.status === "running" || task.status === "waiting" ? { ...task, status: "cancelled", finishedAt: new Date().toISOString(), error: reason, graph: task.graph ? { ...task.graph, queue: "done" } : undefined } : task);
|
|
487
489
|
}
|
|
488
490
|
|
|
489
491
|
function hasPendingMutatingAdaptiveTask(tasks: TeamTaskState[]): boolean {
|
|
@@ -533,7 +535,7 @@ export async function executeTeamRun(input: ExecuteTeamRunInput): Promise<{ mani
|
|
|
533
535
|
|
|
534
536
|
while (tasks.some((task) => task.status === "queued")) {
|
|
535
537
|
if (input.signal?.aborted) {
|
|
536
|
-
tasks = tasks.map((task) => task.status === "queued" || task.status === "running" ? { ...task, status: "cancelled", finishedAt: new Date().toISOString(), error: "Run cancelled." } : task);
|
|
538
|
+
tasks = tasks.map((task) => task.status === "queued" || task.status === "running" || task.status === "waiting" ? { ...task, status: "cancelled", finishedAt: new Date().toISOString(), error: "Run cancelled." } : task);
|
|
537
539
|
await saveRunTasksAsync(manifest, tasks);
|
|
538
540
|
manifest = updateRunStatus(manifest, "cancelled", "Run cancelled.");
|
|
539
541
|
return { manifest, tasks };
|
|
@@ -579,7 +581,7 @@ export async function executeTeamRun(input: ExecuteTeamRunInput): Promise<{ mani
|
|
|
579
581
|
async (task) => {
|
|
580
582
|
const step = findStep(workflow, task);
|
|
581
583
|
const agent = findAgent(input.agents, task);
|
|
582
|
-
const baseInput = { manifest, tasks, task, step, agent, signal: input.signal, executeWorkers: input.executeWorkers, runtimeKind: input.runtime?.kind, runtimeConfig: input.runtimeConfig, parentContext: input.parentContext, parentModel: input.parentModel, modelRegistry: input.modelRegistry, modelOverride: input.modelOverride, limits: input.limits };
|
|
584
|
+
const baseInput = { manifest, tasks, task, step, agent, signal: input.signal, executeWorkers: input.executeWorkers, runtimeKind: input.runtime?.kind, runtimeConfig: input.runtimeConfig, parentContext: input.parentContext, parentModel: input.parentModel, modelRegistry: input.modelRegistry, modelOverride: input.modelOverride, limits: input.limits, onJsonEvent: input.onJsonEvent };
|
|
583
585
|
if (input.reliability?.autoRetry !== true) return withCorrelation(childCorrelation(manifest.runId, task.id), () => runTeamTask(baseInput));
|
|
584
586
|
let lastFailed: { manifest: TeamRunManifest; tasks: TeamTaskState[] } | undefined;
|
|
585
587
|
const attemptsSoFar: TaskAttemptState[] = [...(task.attempts ?? [])];
|
|
@@ -589,8 +591,12 @@ export async function executeTeamRun(input: ExecuteTeamRunInput): Promise<{ mani
|
|
|
589
591
|
const startedAt = new Date().toISOString();
|
|
590
592
|
const inFlightAttempts: TaskAttemptState[] = [...attemptsSoFar, { startedAt }];
|
|
591
593
|
input.metricRegistry?.counter("crew.task.retry_attempt_total", "Retry attempts by run and task").inc({ runId: manifest.runId, taskId: task.id });
|
|
592
|
-
const
|
|
593
|
-
const
|
|
594
|
+
const fresh = loadRunManifestById(manifest.cwd, manifest.runId);
|
|
595
|
+
const freshManifest = fresh?.manifest ?? manifest;
|
|
596
|
+
const freshTasks = fresh?.tasks ?? tasks;
|
|
597
|
+
const freshTask = freshTasks.find((item) => item.id === task.id) ?? task;
|
|
598
|
+
const taskWithAttempt: TeamTaskState = { ...freshTask, attempts: inFlightAttempts };
|
|
599
|
+
const result = await withCorrelation(childCorrelation(freshManifest.runId, task.id), () => runTeamTask({ ...baseInput, manifest: freshManifest, tasks: freshTasks, task: taskWithAttempt }));
|
|
594
600
|
const failed = failedTaskFrom(result, task.id);
|
|
595
601
|
const endedAt = new Date().toISOString();
|
|
596
602
|
const finishedAttempt: TaskAttemptState = { startedAt, endedAt, ...(failed?.error ? { error: failed.error } : {}) };
|
|
@@ -616,7 +622,12 @@ export async function executeTeamRun(input: ExecuteTeamRunInput): Promise<{ mani
|
|
|
616
622
|
},
|
|
617
623
|
});
|
|
618
624
|
} catch {
|
|
619
|
-
|
|
625
|
+
if (lastFailed) return lastFailed;
|
|
626
|
+
const fresh = loadRunManifestById(manifest.cwd, manifest.runId);
|
|
627
|
+
const freshManifest = fresh?.manifest ?? manifest;
|
|
628
|
+
const freshTasks = fresh?.tasks ?? tasks;
|
|
629
|
+
const freshTask = freshTasks.find((item) => item.id === task.id) ?? task;
|
|
630
|
+
return withCorrelation(childCorrelation(freshManifest.runId, task.id), () => runTeamTask({ ...baseInput, manifest: freshManifest, tasks: freshTasks, task: freshTask }));
|
|
620
631
|
}
|
|
621
632
|
},
|
|
622
633
|
);
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
export interface WorkerHeartbeatState {
|
|
2
|
-
workerId: string;
|
|
3
|
-
pid?: number;
|
|
4
|
-
lastSeenAt: string;
|
|
5
|
-
lastStdoutAt?: string;
|
|
6
|
-
lastEventAt?: string;
|
|
7
|
-
turnCount?: number;
|
|
8
|
-
alive?: boolean;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export function createWorkerHeartbeat(workerId: string, pid?: number, now = new Date()): WorkerHeartbeatState {
|
|
12
|
-
return { workerId, pid, lastSeenAt: now.toISOString(), alive: true };
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function touchWorkerHeartbeat(heartbeat: WorkerHeartbeatState, updates: Partial<Omit<WorkerHeartbeatState, "workerId">> = {}, now = new Date()): WorkerHeartbeatState {
|
|
16
|
-
return { ...heartbeat, ...updates, lastSeenAt: now.toISOString() };
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export function isWorkerHeartbeatStale(heartbeat: WorkerHeartbeatState, staleMs: number, now = new Date()): boolean {
|
|
20
|
-
return now.getTime() - Date.parse(heartbeat.lastSeenAt) > staleMs;
|
|
21
|
-
}
|
|
1
|
+
export interface WorkerHeartbeatState {
|
|
2
|
+
workerId: string;
|
|
3
|
+
pid?: number;
|
|
4
|
+
lastSeenAt: string;
|
|
5
|
+
lastStdoutAt?: string;
|
|
6
|
+
lastEventAt?: string;
|
|
7
|
+
turnCount?: number;
|
|
8
|
+
alive?: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function createWorkerHeartbeat(workerId: string, pid?: number, now = new Date()): WorkerHeartbeatState {
|
|
12
|
+
return { workerId, pid, lastSeenAt: now.toISOString(), alive: true };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function touchWorkerHeartbeat(heartbeat: WorkerHeartbeatState, updates: Partial<Omit<WorkerHeartbeatState, "workerId">> = {}, now = new Date()): WorkerHeartbeatState {
|
|
16
|
+
return { ...heartbeat, ...updates, lastSeenAt: now.toISOString() };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function isWorkerHeartbeatStale(heartbeat: WorkerHeartbeatState, staleMs: number, now = new Date()): boolean {
|
|
20
|
+
return now.getTime() - Date.parse(heartbeat.lastSeenAt) > staleMs;
|
|
21
|
+
}
|
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
export type WorkerLifecycleState = "spawning" | "trust_required" | "ready_for_prompt" | "running" | "finished" | "failed";
|
|
2
|
-
export type StartupFailureClassification = "trust_required" | "prompt_misdelivery" | "prompt_acceptance_timeout" | "transport_dead" | "worker_crashed" | "unknown";
|
|
3
|
-
|
|
4
|
-
export interface WorkerStartupEvidence {
|
|
5
|
-
lastLifecycleState: WorkerLifecycleState;
|
|
6
|
-
command: string;
|
|
7
|
-
promptSentAt?: string;
|
|
8
|
-
promptAccepted: boolean;
|
|
9
|
-
trustPromptDetected: boolean;
|
|
10
|
-
transportHealthy: boolean;
|
|
11
|
-
childProcessAlive: boolean;
|
|
12
|
-
elapsedMs: number;
|
|
13
|
-
classification: StartupFailureClassification;
|
|
14
|
-
stderrPreview?: string;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function detectTrustPrompt(text: string): boolean {
|
|
18
|
-
const lowered = text.toLowerCase();
|
|
19
|
-
return lowered.includes("do you trust") || lowered.includes("trust this") || lowered.includes("untrusted") || lowered.includes("workspace trust") || lowered.includes("allow this folder");
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function classifyStartupFailure(evidence: Omit<WorkerStartupEvidence, "classification">): StartupFailureClassification {
|
|
23
|
-
if (!evidence.transportHealthy) return "transport_dead";
|
|
24
|
-
if (evidence.trustPromptDetected || evidence.lastLifecycleState === "trust_required") return "trust_required";
|
|
25
|
-
if (evidence.promptSentAt && !evidence.promptAccepted && evidence.childProcessAlive) return "prompt_acceptance_timeout";
|
|
26
|
-
if (evidence.promptSentAt && !evidence.promptAccepted && !evidence.childProcessAlive) return "worker_crashed";
|
|
27
|
-
if (evidence.stderrPreview?.toLowerCase().includes("command not found") || evidence.stderrPreview?.toLowerCase().includes("not recognized")) return "prompt_misdelivery";
|
|
28
|
-
if (!evidence.childProcessAlive && evidence.lastLifecycleState !== "finished") return "worker_crashed";
|
|
29
|
-
return "unknown";
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function createStartupEvidence(input: {
|
|
33
|
-
command: string;
|
|
34
|
-
startedAt: Date;
|
|
35
|
-
finishedAt?: Date;
|
|
36
|
-
promptSentAt?: Date;
|
|
37
|
-
promptAccepted?: boolean;
|
|
38
|
-
stderr?: string;
|
|
39
|
-
error?: string;
|
|
40
|
-
exitCode?: number | null;
|
|
41
|
-
}): WorkerStartupEvidence {
|
|
42
|
-
const stderrPreview = (input.error || input.stderr || "").slice(0, 500) || undefined;
|
|
43
|
-
const trustPromptDetected = detectTrustPrompt(stderrPreview ?? "");
|
|
44
|
-
const childProcessAlive = input.exitCode === undefined || input.exitCode === null ? !input.finishedAt : false;
|
|
45
|
-
const base: Omit<WorkerStartupEvidence, "classification"> = {
|
|
46
|
-
lastLifecycleState: input.error || (input.exitCode !== undefined && input.exitCode !== null && input.exitCode !== 0) ? "failed" : input.finishedAt ? "finished" : "running",
|
|
47
|
-
command: input.command,
|
|
48
|
-
promptSentAt: input.promptSentAt?.toISOString(),
|
|
49
|
-
promptAccepted: input.promptAccepted ?? !input.error,
|
|
50
|
-
trustPromptDetected,
|
|
51
|
-
transportHealthy: !input.error || !/enoent|spawn|transport/i.test(input.error),
|
|
52
|
-
childProcessAlive,
|
|
53
|
-
elapsedMs: Math.max(0, (input.finishedAt ?? new Date()).getTime() - input.startedAt.getTime()),
|
|
54
|
-
stderrPreview,
|
|
55
|
-
};
|
|
56
|
-
return { ...base, classification: classifyStartupFailure(base) };
|
|
57
|
-
}
|
|
1
|
+
export type WorkerLifecycleState = "spawning" | "trust_required" | "ready_for_prompt" | "running" | "finished" | "failed";
|
|
2
|
+
export type StartupFailureClassification = "trust_required" | "prompt_misdelivery" | "prompt_acceptance_timeout" | "transport_dead" | "worker_crashed" | "unknown";
|
|
3
|
+
|
|
4
|
+
export interface WorkerStartupEvidence {
|
|
5
|
+
lastLifecycleState: WorkerLifecycleState;
|
|
6
|
+
command: string;
|
|
7
|
+
promptSentAt?: string;
|
|
8
|
+
promptAccepted: boolean;
|
|
9
|
+
trustPromptDetected: boolean;
|
|
10
|
+
transportHealthy: boolean;
|
|
11
|
+
childProcessAlive: boolean;
|
|
12
|
+
elapsedMs: number;
|
|
13
|
+
classification: StartupFailureClassification;
|
|
14
|
+
stderrPreview?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function detectTrustPrompt(text: string): boolean {
|
|
18
|
+
const lowered = text.toLowerCase();
|
|
19
|
+
return lowered.includes("do you trust") || lowered.includes("trust this") || lowered.includes("untrusted") || lowered.includes("workspace trust") || lowered.includes("allow this folder");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function classifyStartupFailure(evidence: Omit<WorkerStartupEvidence, "classification">): StartupFailureClassification {
|
|
23
|
+
if (!evidence.transportHealthy) return "transport_dead";
|
|
24
|
+
if (evidence.trustPromptDetected || evidence.lastLifecycleState === "trust_required") return "trust_required";
|
|
25
|
+
if (evidence.promptSentAt && !evidence.promptAccepted && evidence.childProcessAlive) return "prompt_acceptance_timeout";
|
|
26
|
+
if (evidence.promptSentAt && !evidence.promptAccepted && !evidence.childProcessAlive) return "worker_crashed";
|
|
27
|
+
if (evidence.stderrPreview?.toLowerCase().includes("command not found") || evidence.stderrPreview?.toLowerCase().includes("not recognized")) return "prompt_misdelivery";
|
|
28
|
+
if (!evidence.childProcessAlive && evidence.lastLifecycleState !== "finished") return "worker_crashed";
|
|
29
|
+
return "unknown";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function createStartupEvidence(input: {
|
|
33
|
+
command: string;
|
|
34
|
+
startedAt: Date;
|
|
35
|
+
finishedAt?: Date;
|
|
36
|
+
promptSentAt?: Date;
|
|
37
|
+
promptAccepted?: boolean;
|
|
38
|
+
stderr?: string;
|
|
39
|
+
error?: string;
|
|
40
|
+
exitCode?: number | null;
|
|
41
|
+
}): WorkerStartupEvidence {
|
|
42
|
+
const stderrPreview = (input.error || input.stderr || "").slice(0, 500) || undefined;
|
|
43
|
+
const trustPromptDetected = detectTrustPrompt(stderrPreview ?? "");
|
|
44
|
+
const childProcessAlive = input.exitCode === undefined || input.exitCode === null ? !input.finishedAt : false;
|
|
45
|
+
const base: Omit<WorkerStartupEvidence, "classification"> = {
|
|
46
|
+
lastLifecycleState: input.error || (input.exitCode !== undefined && input.exitCode !== null && input.exitCode !== 0) ? "failed" : input.finishedAt ? "finished" : "running",
|
|
47
|
+
command: input.command,
|
|
48
|
+
promptSentAt: input.promptSentAt?.toISOString(),
|
|
49
|
+
promptAccepted: input.promptAccepted ?? !input.error,
|
|
50
|
+
trustPromptDetected,
|
|
51
|
+
transportHealthy: !input.error || !/enoent|spawn|transport/i.test(input.error),
|
|
52
|
+
childProcessAlive,
|
|
53
|
+
elapsedMs: Math.max(0, (input.finishedAt ?? new Date()).getTime() - input.startedAt.getTime()),
|
|
54
|
+
stderrPreview,
|
|
55
|
+
};
|
|
56
|
+
return { ...base, classification: classifyStartupFailure(base) };
|
|
57
|
+
}
|
|
@@ -58,6 +58,7 @@ export const AgentOverrideSchema = Type.Object({
|
|
|
58
58
|
fallbackModels: Type.Optional(Type.Union([Type.Array(Type.String({ minLength: 1 })), Type.Literal(false)])),
|
|
59
59
|
thinking: Type.Optional(Type.Union([Type.String({ minLength: 1 }), Type.Literal(false)])),
|
|
60
60
|
tools: Type.Optional(Type.Union([Type.Array(Type.String({ minLength: 1 })), Type.Literal(false)])),
|
|
61
|
+
skills: Type.Optional(Type.Union([Type.Array(Type.String({ minLength: 1 })), Type.Literal(false)])),
|
|
61
62
|
}, { additionalProperties: false });
|
|
62
63
|
|
|
63
64
|
export const PiTeamsAgentsConfigSchema = Type.Object({
|