@xzzpig/pi-subagents 0.1.0
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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { renderWidget, widgetRenderKey } from "../../tui/render.ts";
|
|
5
|
+
import { formatControlNoticeMessage } from "../shared/subagent-control.ts";
|
|
6
|
+
import {
|
|
7
|
+
type AsyncJobState,
|
|
8
|
+
type AsyncStartedEvent,
|
|
9
|
+
type ControlEvent,
|
|
10
|
+
type SteeringNotice,
|
|
11
|
+
type SubagentState,
|
|
12
|
+
POLL_INTERVAL_MS,
|
|
13
|
+
DIRS,
|
|
14
|
+
SUBAGENT_CONTROL_EVENT,
|
|
15
|
+
SUBAGENT_CONTROL_INTERCOM_EVENT,
|
|
16
|
+
SUBAGENT_STEERING_NOTICE_EVENT,
|
|
17
|
+
} from "../../shared/types.ts";
|
|
18
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
19
|
+
import { normalizeParallelGroups } from "./parallel-groups.ts";
|
|
20
|
+
import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-reconciler.ts";
|
|
21
|
+
import { hasLiveNestedDescendants, updateAsyncJobNestedProjection } from "../shared/nested-events.ts";
|
|
22
|
+
import { listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
|
|
23
|
+
|
|
24
|
+
interface AsyncJobTrackerOptions {
|
|
25
|
+
completionRetentionMs?: number;
|
|
26
|
+
pollIntervalMs?: number;
|
|
27
|
+
resultsDir?: string;
|
|
28
|
+
widgetEnabled?: boolean;
|
|
29
|
+
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
30
|
+
now?: () => number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const CONTROL_EVENT_READ_CHUNK_BYTES = 64 * 1024;
|
|
34
|
+
const MAX_CONTROL_EVENT_LINE_BYTES = 1024 * 1024;
|
|
35
|
+
const CONTROL_EVENT_SCAN_WINDOW_BYTES = 2 * 1024 * 1024;
|
|
36
|
+
const MAX_RECENT_FLEET_JOBS = 20;
|
|
37
|
+
|
|
38
|
+
function rememberFleetJob(state: SubagentState, job: AsyncJobState): void {
|
|
39
|
+
state.fleetJobs ??= new Map();
|
|
40
|
+
state.fleetJobs.set(job.asyncId, job);
|
|
41
|
+
const terminal = [...state.fleetJobs.values()]
|
|
42
|
+
.filter((candidate) => candidate.status === "complete" || candidate.status === "failed" || candidate.status === "paused" || candidate.status === "stopped")
|
|
43
|
+
.sort((left, right) => (right.updatedAt ?? right.startedAt ?? 0) - (left.updatedAt ?? left.startedAt ?? 0));
|
|
44
|
+
for (const stale of terminal.slice(MAX_RECENT_FLEET_JOBS)) state.fleetJobs.delete(stale.asyncId);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: SubagentState, asyncDirRoot: string, options: AsyncJobTrackerOptions = {}): {
|
|
48
|
+
ensurePoller: () => void;
|
|
49
|
+
refreshWidget: (ctx: ExtensionContext) => void;
|
|
50
|
+
handleStarted: (data: unknown) => void;
|
|
51
|
+
handleComplete: (data: unknown) => void;
|
|
52
|
+
resetJobs: (ctx?: ExtensionContext) => void;
|
|
53
|
+
restoreActiveJobs: (ctx?: ExtensionContext) => void;
|
|
54
|
+
} {
|
|
55
|
+
const completionRetentionMs = options.completionRetentionMs ?? 10000;
|
|
56
|
+
const pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;
|
|
57
|
+
const resultsDir = options.resultsDir ?? DIRS.results;
|
|
58
|
+
const steeringNoticeSeen = new Map<string, number>();
|
|
59
|
+
const rerenderWidget = (ctx: ExtensionContext, jobs = Array.from(state.asyncJobs.values())) => {
|
|
60
|
+
renderWidget(ctx, options.widgetEnabled === false ? [] : jobs);
|
|
61
|
+
(ctx.ui as { requestRender?: () => void }).requestRender?.();
|
|
62
|
+
};
|
|
63
|
+
const rerenderLastWidget = (jobs = Array.from(state.asyncJobs.values())) => {
|
|
64
|
+
const ctx = state.lastUiContext;
|
|
65
|
+
if (!ctx) return;
|
|
66
|
+
try {
|
|
67
|
+
if (ctx.hasUI) rerenderWidget(ctx, jobs);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error instanceof Error && error.message.includes("extension ctx is stale")) {
|
|
70
|
+
state.lastUiContext = null;
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const refreshWidget = (ctx: ExtensionContext) => rerenderWidget(ctx);
|
|
77
|
+
const restoredControlEventCursor = (asyncDir: string) => {
|
|
78
|
+
try {
|
|
79
|
+
return fs.statSync(path.join(asyncDir, "events.jsonl")).size;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return 0;
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const summaryToJob = (run: AsyncRunSummary): AsyncJobState => {
|
|
86
|
+
const groups = normalizeParallelGroups(run.parallelGroups, run.steps.length, run.chainStepCount ?? run.steps.length);
|
|
87
|
+
const activeGroup = run.currentStep !== undefined
|
|
88
|
+
? groups.find((group) => run.currentStep! >= group.start && run.currentStep! < group.start + group.count)
|
|
89
|
+
: undefined;
|
|
90
|
+
const visibleSteps = activeGroup
|
|
91
|
+
? run.steps.slice(activeGroup.start, activeGroup.start + activeGroup.count).map((step, index) => ({ ...step, index: activeGroup.start + index }))
|
|
92
|
+
: run.steps.map((step, index) => ({ ...step, index }));
|
|
93
|
+
return {
|
|
94
|
+
asyncId: run.id,
|
|
95
|
+
asyncDir: run.asyncDir,
|
|
96
|
+
status: run.state,
|
|
97
|
+
sessionId: run.sessionId,
|
|
98
|
+
activityState: run.activityState,
|
|
99
|
+
lastActivityAt: run.lastActivityAt,
|
|
100
|
+
currentTool: run.currentTool,
|
|
101
|
+
currentToolStartedAt: run.currentToolStartedAt,
|
|
102
|
+
currentPath: run.currentPath,
|
|
103
|
+
turnCount: run.turnCount,
|
|
104
|
+
toolCount: run.toolCount,
|
|
105
|
+
steering: run.steering,
|
|
106
|
+
mode: run.mode,
|
|
107
|
+
context: run.context,
|
|
108
|
+
cwd: run.cwd,
|
|
109
|
+
agents: visibleSteps.map((step) => step.agent),
|
|
110
|
+
currentStep: run.currentStep,
|
|
111
|
+
chainStepCount: run.chainStepCount,
|
|
112
|
+
parallelGroups: groups,
|
|
113
|
+
steps: visibleSteps,
|
|
114
|
+
stepsTotal: visibleSteps.length,
|
|
115
|
+
runningSteps: visibleSteps.filter((step) => step.status === "running").length,
|
|
116
|
+
completedSteps: visibleSteps.filter((step) => step.status === "complete" || step.status === "completed").length,
|
|
117
|
+
hasParallelGroups: groups.length > 0,
|
|
118
|
+
activeParallelGroup: Boolean(activeGroup),
|
|
119
|
+
startedAt: run.startedAt,
|
|
120
|
+
updatedAt: run.lastUpdate ?? run.startedAt,
|
|
121
|
+
timeoutMs: run.timeoutMs,
|
|
122
|
+
deadlineAt: run.deadlineAt,
|
|
123
|
+
timedOut: run.timedOut,
|
|
124
|
+
stopped: run.stopped,
|
|
125
|
+
turnBudget: run.turnBudget,
|
|
126
|
+
turnBudgetExceeded: run.turnBudgetExceeded,
|
|
127
|
+
wrapUpRequested: run.wrapUpRequested,
|
|
128
|
+
sessionDir: run.sessionDir,
|
|
129
|
+
outputFile: run.outputFile,
|
|
130
|
+
totalTokens: run.totalTokens,
|
|
131
|
+
sessionFile: run.sessionFile,
|
|
132
|
+
controlEventCursor: restoredControlEventCursor(run.asyncDir),
|
|
133
|
+
nestedChildren: run.nestedChildren,
|
|
134
|
+
parentWorkflowRunId: run.parentWorkflowRunId,
|
|
135
|
+
workflowKey: run.workflowKey,
|
|
136
|
+
workflow: run.workflow,
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
const cancelCleanup = (asyncId: string) => {
|
|
140
|
+
const existingTimer = state.cleanupTimers.get(asyncId);
|
|
141
|
+
if (!existingTimer) return;
|
|
142
|
+
clearTimeout(existingTimer);
|
|
143
|
+
state.cleanupTimers.delete(asyncId);
|
|
144
|
+
};
|
|
145
|
+
const scheduleCleanup = (asyncId: string) => {
|
|
146
|
+
cancelCleanup(asyncId);
|
|
147
|
+
const timer = setTimeout(() => {
|
|
148
|
+
state.cleanupTimers.delete(asyncId);
|
|
149
|
+
state.asyncJobs.delete(asyncId);
|
|
150
|
+
rerenderLastWidget();
|
|
151
|
+
}, completionRetentionMs);
|
|
152
|
+
state.cleanupTimers.set(asyncId, timer);
|
|
153
|
+
};
|
|
154
|
+
const emitNewControlEvents = (job: AsyncJobState) => {
|
|
155
|
+
const eventsPath = path.join(job.asyncDir, "events.jsonl");
|
|
156
|
+
let fd: number;
|
|
157
|
+
try {
|
|
158
|
+
fd = fs.openSync(eventsPath, "r");
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
161
|
+
console.error(`Failed to open async control events for '${job.asyncDir}':`, error);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
const stat = fs.fstatSync(fd);
|
|
166
|
+
const savedCursor = job.controlEventCursor;
|
|
167
|
+
let cursor = stat.size < (savedCursor ?? 0) ? 0 : (savedCursor ?? 0);
|
|
168
|
+
const startedFromTail = savedCursor === undefined && stat.size > CONTROL_EVENT_SCAN_WINDOW_BYTES;
|
|
169
|
+
if (startedFromTail) cursor = stat.size - CONTROL_EVENT_SCAN_WINDOW_BYTES;
|
|
170
|
+
if (stat.size <= cursor) return;
|
|
171
|
+
const previousByte = Buffer.alloc(1);
|
|
172
|
+
const startsMidLine = cursor > 0
|
|
173
|
+
&& fs.readSync(fd, previousByte, 0, 1, cursor - 1) === 1
|
|
174
|
+
&& previousByte[0] !== 0x0a;
|
|
175
|
+
const scanEnd = Math.min(stat.size, cursor + CONTROL_EVENT_SCAN_WINDOW_BYTES);
|
|
176
|
+
const handleLine = (line: string) => {
|
|
177
|
+
if (!line.trim()) return;
|
|
178
|
+
let parsed: unknown;
|
|
179
|
+
try {
|
|
180
|
+
parsed = JSON.parse(line);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
console.error(`Ignoring malformed async control event in '${eventsPath}':`, error);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (!parsed || typeof parsed !== "object") return;
|
|
186
|
+
if ((parsed as { type?: unknown }).type === "subagent.steering.notice") {
|
|
187
|
+
const notice = parsed as Partial<SteeringNotice>;
|
|
188
|
+
if (typeof notice.requestId !== "string" || typeof notice.runId !== "string" || (notice.state !== "failed" && notice.state !== "partial" && notice.state !== "recovered") || typeof notice.message !== "string") return;
|
|
189
|
+
if (typeof state.currentSessionId === "string" && notice.currentSessionId !== state.currentSessionId) return;
|
|
190
|
+
const key = `${notice.runId}:${notice.requestId}:${notice.state}`;
|
|
191
|
+
if (steeringNoticeSeen.has(key)) return;
|
|
192
|
+
const now = Date.now();
|
|
193
|
+
steeringNoticeSeen.set(key, now);
|
|
194
|
+
if (steeringNoticeSeen.size > 200) {
|
|
195
|
+
for (const [seenKey, seenAt] of steeringNoticeSeen) {
|
|
196
|
+
if (now - seenAt > 10 * 60 * 1000 || steeringNoticeSeen.size > 200) steeringNoticeSeen.delete(seenKey);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
pi.events.emit(SUBAGENT_STEERING_NOTICE_EVENT, { ...notice, source: "async", asyncDir: job.asyncDir, noticeText: notice.message });
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
if ((parsed as { type?: unknown }).type !== "subagent.control") return;
|
|
203
|
+
const record = parsed as { event?: ControlEvent; channels?: string[]; childIntercomTarget?: string; noticeText?: string; intercom?: { to?: string; message?: string } };
|
|
204
|
+
if (!record.event || !Array.isArray(record.channels)) return;
|
|
205
|
+
const payload = {
|
|
206
|
+
event: record.event,
|
|
207
|
+
source: "async" as const,
|
|
208
|
+
asyncDir: job.asyncDir,
|
|
209
|
+
childIntercomTarget: record.childIntercomTarget,
|
|
210
|
+
noticeText: record.noticeText ?? formatControlNoticeMessage(record.event, record.childIntercomTarget),
|
|
211
|
+
};
|
|
212
|
+
if (record.channels.includes("event")) {
|
|
213
|
+
pi.events.emit(SUBAGENT_CONTROL_EVENT, payload);
|
|
214
|
+
}
|
|
215
|
+
if (record.event.type !== "active_long_running" && record.channels.includes("intercom") && record.intercom?.to && record.intercom.message) {
|
|
216
|
+
pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {
|
|
217
|
+
...payload,
|
|
218
|
+
to: record.intercom.to,
|
|
219
|
+
message: record.intercom.message,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
let readCursor = cursor;
|
|
224
|
+
let lastCompleteCursor = cursor;
|
|
225
|
+
let lineParts: Buffer[] = [];
|
|
226
|
+
let lineBytes = 0;
|
|
227
|
+
let skippingOversizedLine = startedFromTail || startsMidLine;
|
|
228
|
+
const appendLineSegment = (segment: Buffer) => {
|
|
229
|
+
if (segment.length === 0 || skippingOversizedLine) return;
|
|
230
|
+
if (lineBytes + segment.length > MAX_CONTROL_EVENT_LINE_BYTES) {
|
|
231
|
+
lineParts = [];
|
|
232
|
+
lineBytes = 0;
|
|
233
|
+
skippingOversizedLine = true;
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
lineParts.push(segment);
|
|
237
|
+
lineBytes += segment.length;
|
|
238
|
+
};
|
|
239
|
+
while (readCursor < scanEnd) {
|
|
240
|
+
const toRead = Math.min(CONTROL_EVENT_READ_CHUNK_BYTES, scanEnd - readCursor);
|
|
241
|
+
const buffer = Buffer.alloc(toRead);
|
|
242
|
+
const bytesRead = fs.readSync(fd, buffer, 0, toRead, readCursor);
|
|
243
|
+
if (bytesRead <= 0) break;
|
|
244
|
+
const chunk = bytesRead === buffer.length ? buffer : buffer.subarray(0, bytesRead);
|
|
245
|
+
let lineStart = 0;
|
|
246
|
+
for (let index = 0; index < chunk.length; index++) {
|
|
247
|
+
if (chunk[index] !== 0x0a) continue;
|
|
248
|
+
appendLineSegment(chunk.subarray(lineStart, index));
|
|
249
|
+
if (!skippingOversizedLine && lineBytes > 0) {
|
|
250
|
+
handleLine(Buffer.concat(lineParts, lineBytes).toString("utf-8"));
|
|
251
|
+
}
|
|
252
|
+
lineParts = [];
|
|
253
|
+
lineBytes = 0;
|
|
254
|
+
skippingOversizedLine = false;
|
|
255
|
+
lastCompleteCursor = readCursor + index + 1;
|
|
256
|
+
lineStart = index + 1;
|
|
257
|
+
}
|
|
258
|
+
appendLineSegment(chunk.subarray(lineStart));
|
|
259
|
+
readCursor += bytesRead;
|
|
260
|
+
if (skippingOversizedLine) job.controlEventCursor = readCursor;
|
|
261
|
+
}
|
|
262
|
+
if (lastCompleteCursor > cursor) job.controlEventCursor = lastCompleteCursor;
|
|
263
|
+
else if (scanEnd < stat.size || startedFromTail) job.controlEventCursor = scanEnd;
|
|
264
|
+
} catch (error) {
|
|
265
|
+
console.error(`Failed to read async control events for '${job.asyncDir}':`, error);
|
|
266
|
+
} finally {
|
|
267
|
+
fs.closeSync(fd);
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
const ensurePoller = () => {
|
|
272
|
+
if (state.poller) return;
|
|
273
|
+
state.poller = setInterval(() => {
|
|
274
|
+
if (state.asyncJobs.size === 0) {
|
|
275
|
+
rerenderLastWidget([]);
|
|
276
|
+
if (state.poller) {
|
|
277
|
+
clearInterval(state.poller);
|
|
278
|
+
state.poller = null;
|
|
279
|
+
}
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
let widgetChanged = false;
|
|
284
|
+
for (const job of state.asyncJobs.values()) {
|
|
285
|
+
const widgetStateBefore = widgetRenderKey(job);
|
|
286
|
+
let nestedRefreshFailed = false;
|
|
287
|
+
const refreshNestedProjection = () => {
|
|
288
|
+
try {
|
|
289
|
+
updateAsyncJobNestedProjection(job);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
nestedRefreshFailed = true;
|
|
292
|
+
console.error(`Failed to refresh nested async descendants for '${job.asyncDir}':`, error);
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
const reconcileNestedDescendants = () => {
|
|
296
|
+
try {
|
|
297
|
+
if (job.nestedRoute) reconcileNestedAsyncDescendants(job.nestedRoute, { resultsDir, kill: options.kill, now: options.now });
|
|
298
|
+
} catch (error) {
|
|
299
|
+
nestedRefreshFailed = true;
|
|
300
|
+
console.error(`Failed to refresh nested async descendants for '${job.asyncDir}':`, error);
|
|
301
|
+
}
|
|
302
|
+
refreshNestedProjection();
|
|
303
|
+
};
|
|
304
|
+
try {
|
|
305
|
+
emitNewControlEvents(job);
|
|
306
|
+
reconcileNestedDescendants();
|
|
307
|
+
const reconciliation = reconcileAsyncRun(job.asyncDir, {
|
|
308
|
+
resultsDir,
|
|
309
|
+
kill: options.kill,
|
|
310
|
+
now: options.now,
|
|
311
|
+
startedRun: {
|
|
312
|
+
runId: job.asyncId,
|
|
313
|
+
pid: job.pid,
|
|
314
|
+
sessionId: job.sessionId,
|
|
315
|
+
mode: job.mode,
|
|
316
|
+
agents: job.agents,
|
|
317
|
+
chainStepCount: job.chainStepCount,
|
|
318
|
+
parallelGroups: job.parallelGroups,
|
|
319
|
+
startedAt: job.startedAt,
|
|
320
|
+
sessionFile: job.sessionFile,
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
const status = reconciliation.status ?? readStatus(job.asyncDir);
|
|
324
|
+
if (status) {
|
|
325
|
+
const previousStatus = job.status;
|
|
326
|
+
job.status = status.state;
|
|
327
|
+
if (job.status !== "complete" && job.status !== "failed" && job.status !== "paused" && job.status !== "stopped") cancelCleanup(job.asyncId);
|
|
328
|
+
job.sessionId = status.sessionId ?? job.sessionId;
|
|
329
|
+
job.activityState = status.activityState;
|
|
330
|
+
job.lastActivityAt = status.lastActivityAt ?? job.lastActivityAt;
|
|
331
|
+
job.currentTool = status.currentTool;
|
|
332
|
+
job.currentToolStartedAt = status.currentToolStartedAt;
|
|
333
|
+
job.currentPath = status.currentPath;
|
|
334
|
+
job.turnCount = status.turnCount ?? job.turnCount;
|
|
335
|
+
job.toolCount = status.toolCount ?? job.toolCount;
|
|
336
|
+
job.steering = status.steering ?? job.steering;
|
|
337
|
+
job.mode = status.mode;
|
|
338
|
+
job.parentWorkflowRunId = status.parentWorkflowRunId ?? job.parentWorkflowRunId;
|
|
339
|
+
job.workflowKey = status.workflowKey ?? job.workflowKey;
|
|
340
|
+
job.workflow = status.workflow ?? job.workflow;
|
|
341
|
+
job.currentStep = status.currentStep ?? job.currentStep;
|
|
342
|
+
job.chainStepCount = status.chainStepCount ?? job.chainStepCount;
|
|
343
|
+
job.startedAt = status.startedAt ?? job.startedAt;
|
|
344
|
+
if (status.lastUpdate !== undefined) job.updatedAt = status.lastUpdate;
|
|
345
|
+
if (status.steps?.length) {
|
|
346
|
+
const groups = normalizeParallelGroups(status.parallelGroups, status.steps.length, status.chainStepCount ?? status.steps.length);
|
|
347
|
+
job.parallelGroups = groups.length ? groups : job.parallelGroups;
|
|
348
|
+
job.hasParallelGroups = groups.length > 0 || job.hasParallelGroups;
|
|
349
|
+
const activeGroup = status.currentStep !== undefined
|
|
350
|
+
? groups.find((group) => status.currentStep! >= group.start && status.currentStep! < group.start + group.count)
|
|
351
|
+
: undefined;
|
|
352
|
+
const visibleSteps = activeGroup
|
|
353
|
+
? status.steps.slice(activeGroup.start, activeGroup.start + activeGroup.count).map((step, index) => ({ ...step, index: activeGroup.start + index }))
|
|
354
|
+
: status.steps.map((step, index) => ({ ...step, index }));
|
|
355
|
+
job.activeParallelGroup = Boolean(activeGroup);
|
|
356
|
+
job.agents = visibleSteps.map((step) => step.agent);
|
|
357
|
+
job.steps = visibleSteps;
|
|
358
|
+
refreshNestedProjection();
|
|
359
|
+
job.stepsTotal = visibleSteps.length;
|
|
360
|
+
job.runningSteps = visibleSteps.filter((step) => step.status === "running").length;
|
|
361
|
+
job.completedSteps = visibleSteps.filter((step) => step.status === "complete" || step.status === "completed").length;
|
|
362
|
+
if (status.state === "complete") job.completedSteps = visibleSteps.length;
|
|
363
|
+
}
|
|
364
|
+
job.sessionDir = status.sessionDir ?? job.sessionDir;
|
|
365
|
+
job.outputFile = status.outputFile ?? job.outputFile;
|
|
366
|
+
job.totalTokens = status.totalTokens ?? job.totalTokens;
|
|
367
|
+
job.timeoutMs = status.timeoutMs ?? job.timeoutMs;
|
|
368
|
+
job.deadlineAt = status.deadlineAt ?? job.deadlineAt;
|
|
369
|
+
job.timedOut = status.timedOut ?? job.timedOut;
|
|
370
|
+
job.stopped = status.stopped ?? job.stopped;
|
|
371
|
+
job.turnBudget = status.turnBudget ?? job.turnBudget;
|
|
372
|
+
job.turnBudgetExceeded = status.turnBudgetExceeded ?? job.turnBudgetExceeded;
|
|
373
|
+
job.wrapUpRequested = status.wrapUpRequested ?? job.wrapUpRequested;
|
|
374
|
+
job.sessionFile = status.sessionFile ?? job.sessionFile;
|
|
375
|
+
if (job.status === "complete" || job.status === "failed" || job.status === "paused" || job.status === "stopped") {
|
|
376
|
+
rememberFleetJob(state, job);
|
|
377
|
+
if (!nestedRefreshFailed && !hasLiveNestedDescendants(job.nestedChildren) && (previousStatus !== job.status || !state.cleanupTimers.has(job.asyncId))) {
|
|
378
|
+
scheduleCleanup(job.asyncId);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
if (widgetRenderKey(job) !== widgetStateBefore) widgetChanged = true;
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (job.status === "queued") {
|
|
385
|
+
job.status = "running";
|
|
386
|
+
job.updatedAt = Date.now();
|
|
387
|
+
}
|
|
388
|
+
} catch (error) {
|
|
389
|
+
if (job.status !== "failed") {
|
|
390
|
+
console.error(`Failed to read async status for '${job.asyncDir}':`, error);
|
|
391
|
+
job.status = "failed";
|
|
392
|
+
job.updatedAt = Date.now();
|
|
393
|
+
}
|
|
394
|
+
rememberFleetJob(state, job);
|
|
395
|
+
if (!hasLiveNestedDescendants(job.nestedChildren) && !state.cleanupTimers.has(job.asyncId)) {
|
|
396
|
+
scheduleCleanup(job.asyncId);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (widgetRenderKey(job) !== widgetStateBefore) widgetChanged = true;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (widgetChanged) rerenderLastWidget();
|
|
403
|
+
}, pollIntervalMs);
|
|
404
|
+
state.poller.unref?.();
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
const handleStarted = (data: unknown) => {
|
|
408
|
+
const info = data as AsyncStartedEvent;
|
|
409
|
+
if (!info.id) return;
|
|
410
|
+
if (typeof state.currentSessionId === "string" && info.sessionId !== state.currentSessionId) return;
|
|
411
|
+
const now = Date.now();
|
|
412
|
+
const asyncDir = info.asyncDir ?? path.join(asyncDirRoot, info.id);
|
|
413
|
+
const rawAgents = info.agents?.length ? info.agents : info.chain && info.chain.length > 0 ? info.chain : info.agent ? [info.agent] : undefined;
|
|
414
|
+
const validParallelGroups = normalizeParallelGroups(info.parallelGroups, Number.MAX_SAFE_INTEGER, info.chainStepCount ?? Number.MAX_SAFE_INTEGER);
|
|
415
|
+
const firstGroup = validParallelGroups.find((group) => group.start === 0);
|
|
416
|
+
const firstGroupCount = firstGroup?.count;
|
|
417
|
+
const agents = firstGroupCount && firstGroupCount > 0
|
|
418
|
+
? rawAgents?.slice(0, firstGroupCount)
|
|
419
|
+
: rawAgents;
|
|
420
|
+
state.asyncJobs.set(info.id, {
|
|
421
|
+
asyncId: info.id,
|
|
422
|
+
asyncDir,
|
|
423
|
+
...(typeof info.cwd === "string" ? { cwd: path.resolve(info.cwd) } : {}),
|
|
424
|
+
status: "queued",
|
|
425
|
+
pid: typeof info.pid === "number" ? info.pid : undefined,
|
|
426
|
+
...(typeof info.sessionId === "string" ? { sessionId: info.sessionId } : {}),
|
|
427
|
+
mode: info.mode ?? (info.chain ? "chain" : "single"),
|
|
428
|
+
description: info.goal ?? info.task,
|
|
429
|
+
agents,
|
|
430
|
+
chainStepCount: info.chainStepCount,
|
|
431
|
+
parallelGroups: validParallelGroups,
|
|
432
|
+
nestedRoute: info.nestedRoute,
|
|
433
|
+
stepsTotal: firstGroupCount ?? agents?.length,
|
|
434
|
+
hasParallelGroups: validParallelGroups.length > 0,
|
|
435
|
+
activeParallelGroup: Boolean(firstGroupCount && firstGroupCount > 0),
|
|
436
|
+
startedAt: now,
|
|
437
|
+
updatedAt: now,
|
|
438
|
+
timeoutMs: info.timeoutMs,
|
|
439
|
+
deadlineAt: info.deadlineAt,
|
|
440
|
+
turnBudget: info.turnBudget,
|
|
441
|
+
parentWorkflowRunId: info.parentWorkflowRunId,
|
|
442
|
+
workflowKey: info.workflowKey,
|
|
443
|
+
controlEventCursor: 0,
|
|
444
|
+
});
|
|
445
|
+
rememberFleetJob(state, state.asyncJobs.get(info.id)!);
|
|
446
|
+
ensurePoller();
|
|
447
|
+
rerenderLastWidget();
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const handleComplete = (data: unknown) => {
|
|
451
|
+
const result = data as { id?: string; success?: boolean; state?: AsyncJobState["status"]; asyncDir?: string; sessionId?: string; stopped?: boolean };
|
|
452
|
+
if (typeof state.currentSessionId === "string" && result.sessionId !== state.currentSessionId) return;
|
|
453
|
+
const asyncId = result.id;
|
|
454
|
+
if (!asyncId) return;
|
|
455
|
+
const job = state.asyncJobs.get(asyncId);
|
|
456
|
+
let nestedRefreshFailed = false;
|
|
457
|
+
if (job) {
|
|
458
|
+
job.status = result.state ?? (result.success ? "complete" : "failed");
|
|
459
|
+
job.stopped = result.stopped ?? job.stopped;
|
|
460
|
+
job.updatedAt = Date.now();
|
|
461
|
+
if (result.asyncDir) job.asyncDir = result.asyncDir;
|
|
462
|
+
try {
|
|
463
|
+
updateAsyncJobNestedProjection(job);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
nestedRefreshFailed = true;
|
|
466
|
+
console.error(`Failed to refresh nested async descendants for '${job.asyncDir}':`, error);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
if (job) rememberFleetJob(state, job);
|
|
470
|
+
rerenderLastWidget();
|
|
471
|
+
if (!nestedRefreshFailed && !hasLiveNestedDescendants(job?.nestedChildren)) scheduleCleanup(asyncId);
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
const resetJobs = (ctx?: ExtensionContext) => {
|
|
475
|
+
for (const timer of state.cleanupTimers.values()) {
|
|
476
|
+
clearTimeout(timer);
|
|
477
|
+
}
|
|
478
|
+
state.cleanupTimers.clear();
|
|
479
|
+
state.asyncJobs.clear();
|
|
480
|
+
state.fleetJobs?.clear();
|
|
481
|
+
state.foregroundControls?.clear();
|
|
482
|
+
state.lastForegroundControlId = null;
|
|
483
|
+
state.resultFileCoalescer.clear();
|
|
484
|
+
if (ctx?.hasUI) {
|
|
485
|
+
state.lastUiContext = ctx;
|
|
486
|
+
rerenderWidget(ctx, []);
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
const restoreActiveJobs = (ctx?: ExtensionContext) => {
|
|
491
|
+
if (ctx?.hasUI) state.lastUiContext = ctx;
|
|
492
|
+
if (!state.currentSessionId) return;
|
|
493
|
+
let runs: AsyncRunSummary[];
|
|
494
|
+
try {
|
|
495
|
+
runs = listAsyncRuns(asyncDirRoot, { states: ["queued", "running"], sessionId: state.currentSessionId, resultsDir, kill: options.kill, now: options.now });
|
|
496
|
+
} catch (error) {
|
|
497
|
+
console.error(`Failed to restore active async jobs from '${asyncDirRoot}':`, error);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
for (const run of runs) {
|
|
501
|
+
const job = summaryToJob(run);
|
|
502
|
+
state.asyncJobs.set(run.id, job);
|
|
503
|
+
rememberFleetJob(state, job);
|
|
504
|
+
}
|
|
505
|
+
if (runs.length === 0) return;
|
|
506
|
+
ensurePoller();
|
|
507
|
+
rerenderLastWidget();
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
return { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs };
|
|
511
|
+
}
|