@timmyjl12/pi-subagents 0.20.0 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +862 -827
- package/README.md +1125 -1080
- package/dist/active-agents-prompt.d.ts +31 -9
- package/dist/active-agents-prompt.js +73 -9
- package/dist/agent-color.js +9 -1
- package/dist/agent-file-toggle.d.ts +1 -1
- package/dist/agent-manager.d.ts +405 -18
- package/dist/agent-manager.js +1661 -131
- package/dist/agent-runner.d.ts +45 -6
- package/dist/agent-runner.js +109 -18
- package/dist/agent-types.d.ts +30 -7
- package/dist/agent-types.js +38 -9
- package/dist/awaited-result.d.ts +37 -0
- package/dist/awaited-result.js +150 -0
- package/dist/child-session-shutdown.d.ts +19 -1
- package/dist/child-session-shutdown.js +60 -11
- package/dist/cleanup-plans.d.ts +10 -0
- package/dist/cleanup-plans.js +112 -0
- package/dist/cross-extension-rpc.d.ts +8 -1
- package/dist/cross-extension-rpc.js +59 -5
- package/dist/custom-agents.d.ts +34 -9
- package/dist/custom-agents.js +308 -111
- package/dist/default-agents.d.ts +1 -1
- package/dist/env.d.ts +1 -1
- package/dist/error-log.d.ts +6 -0
- package/dist/error-log.js +8 -0
- package/dist/force-main-model.d.ts +21 -0
- package/dist/force-main-model.js +28 -0
- package/dist/goal-bridge.d.ts +155 -0
- package/dist/goal-bridge.js +305 -0
- package/dist/group-join.d.ts +5 -1
- package/dist/group-join.js +52 -7
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2827 -333
- package/dist/invocation-config.d.ts +30 -3
- package/dist/invocation-config.js +30 -1
- package/dist/memory.d.ts +1 -1
- package/dist/mention-clone.d.ts +1 -1
- package/dist/model-scope.d.ts +1 -1
- package/dist/nested-tools.d.ts +22 -1
- package/dist/nested-tools.js +120 -26
- package/dist/output-file.d.ts +15 -4
- package/dist/output-file.js +146 -43
- package/dist/prompts.d.ts +1 -1
- package/dist/recovery.d.ts +1 -1
- package/dist/report-cleanup.d.ts +204 -0
- package/dist/report-cleanup.js +1632 -0
- package/dist/report-store.d.ts +738 -0
- package/dist/report-store.js +3616 -0
- package/dist/schedule-store.d.ts +14 -6
- package/dist/schedule-store.js +88 -58
- package/dist/schedule.d.ts +20 -8
- package/dist/schedule.js +135 -74
- package/dist/settings.d.ts +39 -11
- package/dist/settings.js +22 -5
- package/dist/status-note.d.ts +1 -1
- package/dist/structured-output.d.ts +1 -1
- package/dist/types.d.ts +32 -3
- package/dist/ui/agent-mention.d.ts +2 -2
- package/dist/ui/agent-widget.d.ts +82 -13
- package/dist/ui/agent-widget.js +155 -37
- package/dist/ui/cleanup-preview.d.ts +59 -0
- package/dist/ui/cleanup-preview.js +466 -0
- package/dist/ui/conversation-viewer.d.ts +4 -4
- package/dist/ui/conversation-viewer.js +10 -6
- package/dist/ui/fleet-list.d.ts +3 -3
- package/dist/ui/fleet-list.js +3 -3
- package/dist/ui/fleet-overlay.d.ts +37 -6
- package/dist/ui/fleet-overlay.js +214 -18
- package/dist/ui/hub-feed.d.ts +52 -0
- package/dist/ui/hub-feed.js +148 -0
- package/dist/ui/native-transcript.js +5 -1
- package/dist/ui/schedule-menu.d.ts +1 -1
- package/dist/ui/schedule-menu.js +1 -1
- package/dist/ui/workflow-card.d.ts +4 -4
- package/dist/ui/workflow-dialog.d.ts +4 -4
- package/dist/ui/workflow-dialog.js +8 -3
- package/dist/ui/workflow-menu.d.ts +2 -2
- package/dist/usage.d.ts +12 -0
- package/dist/usage.js +28 -1
- package/dist/workflow/entry.d.ts +3 -3
- package/dist/workflow/host.d.ts +7 -4
- package/dist/workflow/host.js +162 -48
- package/dist/workflow/journal.d.ts +23 -7
- package/dist/workflow/journal.js +80 -23
- package/dist/workflow/progress.d.ts +1 -1
- package/dist/workflow/runtime.d.ts +45 -6
- package/dist/workflow/runtime.js +105 -16
- package/dist/workflow/task.d.ts +13 -4
- package/dist/workflow/task.js +7 -1
- package/dist/workflow/tool-description.d.ts +7 -2
- package/dist/workflow/tool-description.js +10 -5
- package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
- package/docs/artifacts.md +93 -0
- package/docs/rpc.md +252 -189
- package/docs/runtime-performance.md +53 -0
- package/docs/workflows.md +48 -18
- package/examples/agent-tool-description.md +2 -2
- package/examples/workflows/review-panel.js +6 -3
- package/package.json +5 -5
- package/src/active-agents-prompt.ts +115 -39
- package/src/agent-color.ts +10 -2
- package/src/agent-file-toggle.ts +2 -2
- package/src/agent-manager.ts +3312 -1601
- package/src/agent-runner.ts +164 -36
- package/src/agent-types.ts +56 -11
- package/src/awaited-result.ts +187 -0
- package/src/child-session-shutdown.ts +114 -46
- package/src/cleanup-plans.ts +112 -0
- package/src/cross-extension-rpc.ts +68 -9
- package/src/custom-agents.ts +384 -112
- package/src/default-agents.ts +1 -1
- package/src/enabled-models.ts +1 -1
- package/src/env.ts +1 -1
- package/src/error-log.ts +10 -1
- package/src/force-main-model.ts +29 -0
- package/src/goal-bridge.ts +468 -0
- package/src/group-join.ts +56 -9
- package/src/index.ts +2987 -349
- package/src/invocation-config.ts +50 -4
- package/src/memory.ts +1 -1
- package/src/mention-clone.ts +3 -3
- package/src/model-scope.ts +1 -1
- package/src/nested-tools.ts +164 -33
- package/src/output-file.ts +168 -46
- package/src/prompts.ts +1 -1
- package/src/recovery.ts +2 -2
- package/src/report-cleanup.ts +2044 -0
- package/src/report-store.ts +4133 -0
- package/src/schedule-store.ts +244 -201
- package/src/schedule.ts +144 -80
- package/src/settings.ts +61 -16
- package/src/skill-loader.ts +1 -1
- package/src/standalone-fallback.ts +2 -2
- package/src/status-note.ts +1 -1
- package/src/structured-output.ts +1 -1
- package/src/types.ts +33 -3
- package/src/ui/agent-mention.ts +3 -3
- package/src/ui/agent-widget.ts +179 -45
- package/src/ui/cleanup-preview.ts +518 -0
- package/src/ui/conversation-viewer.ts +19 -15
- package/src/ui/fleet-list.ts +7 -7
- package/src/ui/fleet-overlay.ts +1048 -847
- package/src/ui/hub-feed.ts +179 -0
- package/src/ui/native-transcript.ts +7 -3
- package/src/ui/schedule-menu.ts +4 -4
- package/src/ui/workflow-card.ts +4 -4
- package/src/ui/workflow-dialog.ts +10 -6
- package/src/ui/workflow-menu.ts +4 -4
- package/src/usage.ts +53 -3
- package/src/workflow/collisions.ts +1 -1
- package/src/workflow/entry.ts +3 -3
- package/src/workflow/host.ts +174 -54
- package/src/workflow/journal.ts +80 -23
- package/src/workflow/progress.ts +1 -1
- package/src/workflow/runtime.ts +146 -23
- package/src/workflow/saved.ts +3 -3
- package/src/workflow/task.ts +18 -7
- package/src/workflow/tool-description.ts +10 -5
package/dist/index.js
CHANGED
|
@@ -11,39 +11,45 @@
|
|
|
11
11
|
* /agents — Interactive agent management menu
|
|
12
12
|
*/
|
|
13
13
|
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
14
|
-
import { isAbsolute, join } from "node:path";
|
|
14
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
15
15
|
import { defineTool, getAgentDir, getSettingsListTheme } from "@earendil-works/pi-coding-agent";
|
|
16
16
|
import { Container, Key, matchesKey, SettingsList, Spacer, Text, TruncatedText } from "@earendil-works/pi-tui";
|
|
17
17
|
import { Type } from "@sinclair/typebox";
|
|
18
18
|
import { abortable } from "./abortable.js";
|
|
19
|
-
import {
|
|
19
|
+
import { ACTIVE_AGENTS_MESSAGE_TYPE, nextActiveAgentsMessage } from "./active-agents-prompt.js";
|
|
20
20
|
import { formatAdvisorStatus } from "./advisor-status.js";
|
|
21
21
|
import { hasAgentBadge, renderAgentName } from "./agent-color.js";
|
|
22
22
|
import { buildNewAgentFile, disableInContent, enableInContent, isEmptyStub, locateAgentFile, personalAgentsDir, projectAgentsDir, serializeAgentFile } from "./agent-file-toggle.js";
|
|
23
23
|
import { AgentManager, isTopLevelAgent, sessionAcceptsSteer } from "./agent-manager.js";
|
|
24
|
-
import { getAgentConversation, getDefaultMaxTurns, getGraceTurns, getRememberAgents, normalizeMaxTurns, resolveEffectiveMaxTurns, SUBAGENT_TOOL_NAMES, setDefaultMaxTurns, setGraceTurns, setRememberAgents, steerAgent } from "./agent-runner.js";
|
|
25
|
-
import { BUILTIN_TOOL_NAMES, getAgentConfig, getAllTypes, getAvailableTypes, getConfig, getFallbackSubagent, isDefaultsDisabled, NO_FALLBACK, registerAgents, resolveSpawnType,
|
|
24
|
+
import { getAgentConversation, getAllowPerCallTurnLimits, getDefaultMaxTurns, getGraceTurns, getRememberAgents, normalizeMaxTurns, resolveEffectiveMaxTurns, SUBAGENT_TOOL_NAMES, setAllowPerCallTurnLimits, setDefaultMaxTurns, setGraceTurns, setRememberAgents, steerAgent } from "./agent-runner.js";
|
|
25
|
+
import { BUILTIN_TOOL_NAMES, buildAgentRegistry, cloneAgentDefinition, getAgentConfig, getAgentConfigIn, getAllTypes, getAvailableTypes, getConfig, getFallbackSubagent, isDefaultsDisabled, NO_FALLBACK, registerAgents, resolveSpawnType, resolveSpawnTypeIn, setDefaultsDisabled, setFallbackSubagent } from "./agent-types.js";
|
|
26
|
+
import { formatArchivedReportLookup, formatFinalReport } from "./awaited-result.js";
|
|
26
27
|
import { inChildSessionContext } from "./child-context.js";
|
|
28
|
+
import { mergeCleanupPlans, partitionCleanupPlan } from "./cleanup-plans.js";
|
|
27
29
|
import { registerRpcHandlers } from "./cross-extension-rpc.js";
|
|
28
|
-
import { loadCustomAgents } from "./custom-agents.js";
|
|
30
|
+
import { loadCustomAgents, loadCustomAgentsAsync } from "./custom-agents.js";
|
|
29
31
|
import { logSubagentIssue } from "./error-log.js";
|
|
32
|
+
import { isForceMainModel, setForceMainModel } from "./force-main-model.js";
|
|
33
|
+
import { SubagentsGoalBridge } from "./goal-bridge.js";
|
|
30
34
|
import { GroupJoinManager } from "./group-join.js";
|
|
31
|
-
import { isolationParam, isPinFallback, resolveAgentInvocationConfig, resolveJoinMode, resolvePinnedModel } from "./invocation-config.js";
|
|
35
|
+
import { isolationParam, isPinFallback, maxTurnsParam, resolveAgentInvocationConfig, resolveJoinMode, resolvePinnedModel } from "./invocation-config.js";
|
|
32
36
|
import { describeMention, handleBase, isReservedHandle, parseMention, resolveHandleToType, stripAgentPrefix } from "./mention.js";
|
|
33
37
|
import { runMentionClone } from "./mention-clone.js";
|
|
34
38
|
import { describeModel, resolveModel } from "./model-resolver.js";
|
|
35
39
|
import { checkModelScope, isScopeModelsEnabled, setScopeModelsEnabled } from "./model-scope.js";
|
|
36
40
|
import { getMaxSubagentDepth, setMaxSubagentDepth } from "./nested-tools.js";
|
|
37
41
|
import { createOutputFilePath, ensureOutputFile, getOutputTranscriptDefault, sessionTaskDir, setOutputTranscriptDefault, streamToOutputFile, writeInitialEntry } from "./output-file.js";
|
|
42
|
+
import { applyCleanup, CleanupApplyError, cleanupReadStateLabel, planCleanup, } from "./report-cleanup.js";
|
|
43
|
+
import { normalizeReportPath, ReportStore, ReportUnavailableError, } from "./report-store.js";
|
|
38
44
|
import { SubagentScheduler } from "./schedule.js";
|
|
39
45
|
import { resolveStorePath, ScheduleStore } from "./schedule-store.js";
|
|
40
46
|
import { applyAndEmitLoaded, loadSettings, saveAndEmitChanged } from "./settings.js";
|
|
41
47
|
import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
|
|
42
48
|
import { readShowTerminalProgress, TerminalProgressTracker } from "./terminal-progress.js";
|
|
43
49
|
import { createMentionProvider, mentionRoster } from "./ui/agent-mention.js";
|
|
44
|
-
import { AgentWidget, buildInvocationTags, describeActivity, fgPreservingNestedStyles, formatCost, formatDuration, formatMs, formatTokens, formatTurns, getDisplayName, getPromptModeLabel, SPINNER, } from "./ui/agent-widget.js";
|
|
50
|
+
import { AgentWidget, buildInvocationTags, describeActivity, fgPreservingNestedStyles, formatCost, formatDuration, formatMs, formatTokens, formatTurns, getDisplayName, getPromptModeLabel, SPINNER, sanitizeRowText, } from "./ui/agent-widget.js";
|
|
51
|
+
import { formatCleanupPreview, showCleanupPreview } from "./ui/cleanup-preview.js";
|
|
45
52
|
import { ConversationViewer } from "./ui/conversation-viewer.js";
|
|
46
|
-
import { FleetList } from "./ui/fleet-list.js";
|
|
47
53
|
import { FleetOverlay } from "./ui/fleet-overlay.js";
|
|
48
54
|
import { showSchedulesMenu } from "./ui/schedule-menu.js";
|
|
49
55
|
import { renderWorkflowCard, renderWorkflowEntryCard } from "./ui/workflow-card.js";
|
|
@@ -55,7 +61,7 @@ import { createWorkflowHost } from "./workflow/host.js";
|
|
|
55
61
|
import { appendJournal, readJournal } from "./workflow/journal.js";
|
|
56
62
|
import { extractMeta, workflowCallName } from "./workflow/meta.js";
|
|
57
63
|
import { elapsedMs } from "./workflow/progress.js";
|
|
58
|
-
import { runWorkflow } from "./workflow/runtime.js";
|
|
64
|
+
import { DEFAULT_WORKFLOW_AGENT_TYPE, runWorkflow } from "./workflow/runtime.js";
|
|
59
65
|
import { resolveWorkflowScript } from "./workflow/saved.js";
|
|
60
66
|
import { completeWorkflowTask, createWorkflowTask, failWorkflowTask, formatWorkflowNotification, resolveResumeTarget, updateWorkflowProgressBatch, workflowResultText, workflowRunId } from "./workflow/task.js";
|
|
61
67
|
import { fullWorkflowToolDescription } from "./workflow/tool-description.js";
|
|
@@ -69,8 +75,11 @@ function textResult(msg, details) {
|
|
|
69
75
|
export function renderRunningAgentStatus(frame, statsText, activity, theme, advisorStatus) {
|
|
70
76
|
const container = new Container();
|
|
71
77
|
container.addChild(new Text(theme.fg("accent", frame) + (statsText ? " " + statsText : ""), 0, 0));
|
|
72
|
-
|
|
73
|
-
|
|
78
|
+
// `statsText` arrives already styled, so only the plain fragments are
|
|
79
|
+
// flattened here: a control byte in either would make one rendered row
|
|
80
|
+
// occupy two terminal rows and desynchronise the host's line diff.
|
|
81
|
+
container.addChild(new Text(theme.fg("dim", ` ⎿ ${sanitizeRowText(activity)}`), 0, 0));
|
|
82
|
+
container.addChild(new TruncatedText(theme.fg("dim", ` ⎿ ${sanitizeRowText(formatAdvisorStatus(advisorStatus))}`), 0, 0));
|
|
74
83
|
return container;
|
|
75
84
|
}
|
|
76
85
|
/** Format an agent's lifetime token total, or "" when zero. */
|
|
@@ -145,7 +154,7 @@ function getStatusLabel(status, error) {
|
|
|
145
154
|
}
|
|
146
155
|
}
|
|
147
156
|
/** Format a structured task notification matching Claude Code's <task-notification> XML. */
|
|
148
|
-
function formatTaskNotification(record,
|
|
157
|
+
function formatTaskNotification(record, request, showCost = false) {
|
|
149
158
|
const status = getStatusLabel(record.status, record.error);
|
|
150
159
|
const durationMs = record.completedAt ? record.completedAt - record.startedAt : 0;
|
|
151
160
|
const totalTokens = getLifetimeTotal(record.lifetimeUsage);
|
|
@@ -156,11 +165,10 @@ function formatTaskNotification(record, resultMaxLen, showCost = false) {
|
|
|
156
165
|
// did not ask for is a figure it may start reporting unprompted.
|
|
157
166
|
const cost = showCost ? getLifetimeCost(record.lifetimeUsage) : 0;
|
|
158
167
|
const costXml = cost > 0 ? `<estimated_cost_usd>${cost.toFixed(4)}</estimated_cost_usd>` : "";
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
: "No output.";
|
|
168
|
+
// Never a preview and never capped: the completion notification is where the
|
|
169
|
+
// parent actually reads the worker's answer. The rendered notification keeps
|
|
170
|
+
// its own compact 500/300-character preview in `buildNotificationDetails`.
|
|
171
|
+
const report = formatFinalReport(record, request);
|
|
164
172
|
return [
|
|
165
173
|
`<task-notification>`,
|
|
166
174
|
`<task-id>${record.id}</task-id>`,
|
|
@@ -168,7 +176,7 @@ function formatTaskNotification(record, resultMaxLen, showCost = false) {
|
|
|
168
176
|
record.outputFile ? `<output-file>${escapeXml(record.outputFile)}</output-file>` : null,
|
|
169
177
|
`<status>${escapeXml(status)}</status>`,
|
|
170
178
|
`<summary>Agent "${escapeXml(record.description)}" ${record.status}${getStatusNote(record.status)}</summary>`,
|
|
171
|
-
`<result>${escapeXml(
|
|
179
|
+
`<result>${escapeXml(report)}</result>`,
|
|
172
180
|
`<usage><total_tokens>${totalTokens}</total_tokens><tool_uses>${record.toolUses}</tool_uses>${ctxXml}${compactXml}${costXml}<duration_ms>${durationMs}</duration_ms></usage>`,
|
|
173
181
|
`</task-notification>`,
|
|
174
182
|
].filter(Boolean).join('\n');
|
|
@@ -269,7 +277,7 @@ export default function (pi) {
|
|
|
269
277
|
if (inChildSessionContext())
|
|
270
278
|
return;
|
|
271
279
|
// ---- Register custom notification renderer ----
|
|
272
|
-
pi.registerMessageRenderer("subagent-notification", (message, { expanded }, theme) => {
|
|
280
|
+
pi.registerMessageRenderer("subagent-notification", (message, { expanded, outputPad }, theme) => {
|
|
273
281
|
const d = message.details;
|
|
274
282
|
if (!d)
|
|
275
283
|
return undefined;
|
|
@@ -280,7 +288,7 @@ export default function (pi) {
|
|
|
280
288
|
: d.status === "steered" ? "completed (steered)"
|
|
281
289
|
: "completed";
|
|
282
290
|
// Line 1: icon + agent description + status
|
|
283
|
-
let line = `${icon} ${theme.bold(d.description)} ${theme.fg("dim", statusText)}`;
|
|
291
|
+
let line = `${icon} ${theme.bold(sanitizeRowText(d.description))} ${theme.fg("dim", statusText)}`;
|
|
284
292
|
// Line 2: stats
|
|
285
293
|
const parts = [];
|
|
286
294
|
if (d.turnCount > 0)
|
|
@@ -328,7 +336,8 @@ export default function (pi) {
|
|
|
328
336
|
rendered.unshift(theme.fg("dim", `${all.length} agents · ${formatTokens(tokens)} · ${total}`));
|
|
329
337
|
}
|
|
330
338
|
}
|
|
331
|
-
|
|
339
|
+
// pi adds no padding around a custom renderer; match the transcript's.
|
|
340
|
+
return new Text(rendered.join("\n"), outputPad, 0);
|
|
332
341
|
});
|
|
333
342
|
// ---- Workflow run rendered as a session entry ----
|
|
334
343
|
// A workflow launched from the CLI flag has no tool call to hang its result
|
|
@@ -353,6 +362,22 @@ export default function (pi) {
|
|
|
353
362
|
const userAgents = loadCustomAgents(process.cwd(), strict);
|
|
354
363
|
registerAgents(userAgents);
|
|
355
364
|
};
|
|
365
|
+
/**
|
|
366
|
+
* Awaitable refresh for paths that can suspend (Agent tool, resumes,
|
|
367
|
+
* session_start and the menu). It keeps the process registry fresh for the
|
|
368
|
+
* genuinely synchronous callers, but RETURNS the registry built from THIS
|
|
369
|
+
* load: another root may re-register the global registry while this caller is
|
|
370
|
+
* suspended, and resolving from the global after the await would admit a
|
|
371
|
+
* definition this call never read.
|
|
372
|
+
*/
|
|
373
|
+
const reloadCustomAgentsAsync = async (strict = false) => {
|
|
374
|
+
const userAgents = await loadCustomAgentsAsync(process.cwd(), strict);
|
|
375
|
+
// One synchronous block: no reload can interleave between the scoped map
|
|
376
|
+
// and the global re-registration.
|
|
377
|
+
const registry = buildAgentRegistry(userAgents);
|
|
378
|
+
registerAgents(userAgents);
|
|
379
|
+
return registry;
|
|
380
|
+
};
|
|
356
381
|
// Initial load — the only strict one. A bad edit mid-session must not kill the
|
|
357
382
|
// session on the next unrelated spawn, so every later reload keeps warning.
|
|
358
383
|
reloadCustomAgents(strictAgentFiles);
|
|
@@ -373,7 +398,7 @@ export default function (pi) {
|
|
|
373
398
|
/** Show `~$X` next to token counts in the subagent surfaces. */
|
|
374
399
|
let showCost = false;
|
|
375
400
|
function isShowCostEnabled() { return showCost; }
|
|
376
|
-
function setShowCost(b) { showCost = b; widget.update();
|
|
401
|
+
function setShowCost(b) { showCost = b; widget.update(); }
|
|
377
402
|
/** Name the model and thinking level on the widget's running rows. */
|
|
378
403
|
let showModel = false;
|
|
379
404
|
function isShowModelEnabled() { return showModel; }
|
|
@@ -389,8 +414,7 @@ export default function (pi) {
|
|
|
389
414
|
/**
|
|
390
415
|
* The viewer's Ctrl+R shortcut, from any entry point: set the mode and persist it,
|
|
391
416
|
* so the key and `/agents → Settings` stay one setting rather than one per
|
|
392
|
-
* entry point. `ctx` carries only the warning a failed write notifies with
|
|
393
|
-
* and the fleet list may be acting without one.
|
|
417
|
+
* entry point. `ctx` carries only the warning a failed write notifies with.
|
|
394
418
|
*/
|
|
395
419
|
function chooseViewerMarkdown(mode, ctx) {
|
|
396
420
|
setViewerMarkdown(mode);
|
|
@@ -399,7 +423,9 @@ export default function (pi) {
|
|
|
399
423
|
const pendingUsage = new PendingUsagePool();
|
|
400
424
|
// ---- Cancellable pending notifications ----
|
|
401
425
|
// Holds notifications briefly so get_subagent_result can cancel them
|
|
402
|
-
// before they reach pi.sendMessage (fire-and-forget).
|
|
426
|
+
// before they reach pi.sendMessage (fire-and-forget). The send is retained
|
|
427
|
+
// with its timer so shutdown can deliver a workflow notice the run just
|
|
428
|
+
// settled synchronously instead of dropping it with the timer.
|
|
403
429
|
const pendingNudges = new Map();
|
|
404
430
|
const NUDGE_HOLD_MS = 200;
|
|
405
431
|
// A queued result wait must observe completion before its held notification
|
|
@@ -407,26 +433,63 @@ export default function (pi) {
|
|
|
407
433
|
const QUEUE_WAIT_POLL_MS = Math.floor(NUDGE_HOLD_MS / 4);
|
|
408
434
|
function scheduleNudge(key, send, delay = NUDGE_HOLD_MS) {
|
|
409
435
|
cancelNudge(key);
|
|
410
|
-
|
|
436
|
+
const timer = setTimeout(() => {
|
|
411
437
|
pendingNudges.delete(key);
|
|
412
438
|
try {
|
|
413
439
|
send();
|
|
414
440
|
}
|
|
415
441
|
catch { /* ignore stale completion side-effect errors */ }
|
|
416
|
-
}, delay)
|
|
442
|
+
}, delay);
|
|
443
|
+
pendingNudges.set(key, { timer, send });
|
|
417
444
|
}
|
|
418
445
|
function cancelNudge(key) {
|
|
419
|
-
const
|
|
420
|
-
if (
|
|
421
|
-
clearTimeout(timer);
|
|
446
|
+
const entry = pendingNudges.get(key);
|
|
447
|
+
if (entry != null) {
|
|
448
|
+
clearTimeout(entry.timer);
|
|
422
449
|
pendingNudges.delete(key);
|
|
423
450
|
}
|
|
424
451
|
}
|
|
452
|
+
const deferredResultInterest = new Map();
|
|
453
|
+
/** Remember (or upgrade, within one run) that a completion must carry this result. */
|
|
454
|
+
function deferResultDelivery(record, request) {
|
|
455
|
+
const runGeneration = record.runGeneration ?? 0;
|
|
456
|
+
const prior = deferredResultInterest.get(record.id);
|
|
457
|
+
const sameRun = prior?.runGeneration === runGeneration;
|
|
458
|
+
deferredResultInterest.set(record.id, {
|
|
459
|
+
runGeneration,
|
|
460
|
+
verbose: sameRun && prior.verbose ? true : request.verbose,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
/** The interest for the run this record is on now, if any. */
|
|
464
|
+
function currentResultInterest(record) {
|
|
465
|
+
const interest = deferredResultInterest.get(record.id);
|
|
466
|
+
return interest?.runGeneration === (record.runGeneration ?? 0) ? interest : undefined;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Drop interest a terminal delivery has made inert.
|
|
470
|
+
*
|
|
471
|
+
* A completion pinned to `deliveryGeneration` spends any request for that run
|
|
472
|
+
* (it was carried, or the run produced no interest of its own) and any older
|
|
473
|
+
* one (a resume superseded it, so that wait's agent run is gone for good —
|
|
474
|
+
* leaving it behind would only enrich some later, unrelated run). A NEWER
|
|
475
|
+
* request is for a run this delivery cannot speak for, so it is kept.
|
|
476
|
+
*/
|
|
477
|
+
function clearSpentResultInterest(record, deliveryGeneration) {
|
|
478
|
+
const interest = deferredResultInterest.get(record.id);
|
|
479
|
+
if (interest && interest.runGeneration <= deliveryGeneration)
|
|
480
|
+
deferredResultInterest.delete(record.id);
|
|
481
|
+
}
|
|
425
482
|
// ---- Individual nudge helper (async join mode) ----
|
|
426
|
-
function emitIndividualNudge(record) {
|
|
483
|
+
function emitIndividualNudge(record, runGeneration) {
|
|
484
|
+
// Re-check at send time: a resume inside the hold made this completion stale.
|
|
485
|
+
if ((record.runGeneration ?? 0) !== runGeneration)
|
|
486
|
+
return;
|
|
427
487
|
if (record.resultConsumed)
|
|
428
|
-
return;
|
|
429
|
-
const
|
|
488
|
+
return;
|
|
489
|
+
const awaited = currentResultInterest(record);
|
|
490
|
+
// EVERY ordinary completion carries the complete final report — awaited or
|
|
491
|
+
// not. `verbose` is the only thing a wait can add, and it is opt-in.
|
|
492
|
+
const notification = formatTaskNotification(record, awaited ?? { verbose: false }, showCost);
|
|
430
493
|
const footer = record.outputFile ? `\nFull transcript available at: ${record.outputFile}` : '';
|
|
431
494
|
pi.sendMessage({
|
|
432
495
|
customType: "subagent-notification",
|
|
@@ -434,12 +497,16 @@ export default function (pi) {
|
|
|
434
497
|
display: true,
|
|
435
498
|
details: buildNotificationDetails(record, 500, agentActivity.get(record.id)),
|
|
436
499
|
}, { deliverAs: "followUp", triggerTurn: true });
|
|
500
|
+
// Spent: one wakeup per completion, never a supplement. Any older interest
|
|
501
|
+
// for this record is inert now that this run's terminal report went out.
|
|
502
|
+
clearSpentResultInterest(record, runGeneration);
|
|
437
503
|
}
|
|
438
504
|
function sendIndividualNudge(record) {
|
|
505
|
+
// Captured at schedule time; re-checked when the hold expires.
|
|
506
|
+
const runGeneration = record.runGeneration ?? 0;
|
|
439
507
|
agentActivity.delete(record.id);
|
|
440
508
|
widget.markFinished(record.id);
|
|
441
|
-
|
|
442
|
-
scheduleNudge(record.id, () => emitIndividualNudge(record));
|
|
509
|
+
scheduleNudge(record.id, () => emitIndividualNudge(record, runGeneration));
|
|
443
510
|
widget.update();
|
|
444
511
|
}
|
|
445
512
|
// ---- Group join manager ----
|
|
@@ -447,17 +514,24 @@ export default function (pi) {
|
|
|
447
514
|
for (const r of records) {
|
|
448
515
|
agentActivity.delete(r.id);
|
|
449
516
|
widget.markFinished(r.id);
|
|
450
|
-
fleet.onAgentFinished(r.id);
|
|
451
517
|
}
|
|
518
|
+
// Pin each record's run at schedule time; the hold is 200 ms, and a
|
|
519
|
+
// resume inside it must not inherit this completion.
|
|
520
|
+
const completions = records.map(record => ({ record, runGeneration: record.runGeneration ?? 0 }));
|
|
452
521
|
const groupKey = `group:${records.map(r => r.id).join(",")}`;
|
|
453
522
|
scheduleNudge(groupKey, () => {
|
|
454
|
-
|
|
455
|
-
|
|
523
|
+
const unconsumed = completions
|
|
524
|
+
.filter(entry => (entry.record.runGeneration ?? 0) === entry.runGeneration && !entry.record.resultConsumed)
|
|
525
|
+
.map(entry => entry.record);
|
|
456
526
|
if (unconsumed.length === 0) {
|
|
457
527
|
widget.update();
|
|
458
528
|
return;
|
|
459
529
|
}
|
|
460
|
-
|
|
530
|
+
// Every member carries its complete final report. A wait's `verbose`
|
|
531
|
+
// adds its own opt-in transcript excerpt; nothing here is budgeted
|
|
532
|
+
// against the group, because the report itself is never truncated.
|
|
533
|
+
const awaited = unconsumed.filter(r => currentResultInterest(r) !== undefined);
|
|
534
|
+
const notifications = unconsumed.map(r => formatTaskNotification(r, currentResultInterest(r) ?? { verbose: false }, showCost)).join('\n\n');
|
|
461
535
|
const label = partial
|
|
462
536
|
? `${unconsumed.length} agent(s) finished (partial — others still running)`
|
|
463
537
|
: `${unconsumed.length} agent(s) finished`;
|
|
@@ -468,10 +542,18 @@ export default function (pi) {
|
|
|
468
542
|
}
|
|
469
543
|
pi.sendMessage({
|
|
470
544
|
customType: "subagent-notification",
|
|
471
|
-
content: `Background agent group completed: ${label}\n\n${notifications}\n\
|
|
545
|
+
content: `Background agent group completed: ${label}\n\n${notifications}\n\n` +
|
|
546
|
+
`Each agent's complete final report is included above — do not re-request one. ` +
|
|
547
|
+
(awaited.length > 0
|
|
548
|
+
? "A requested wait additionally carries its full conversation as an opt-in transcript excerpt; get_subagent_result(verbose: true) returns a full transcript."
|
|
549
|
+
: "Use get_subagent_result only for a status detail or an explicit raw transcript."),
|
|
472
550
|
display: true,
|
|
473
551
|
details,
|
|
474
552
|
}, { deliverAs: "followUp", triggerTurn: true });
|
|
553
|
+
// One group wakeup spends every request it could speak for — including
|
|
554
|
+
// an older run's request that a resume has already superseded.
|
|
555
|
+
for (const entry of completions)
|
|
556
|
+
clearSpentResultInterest(entry.record, entry.runGeneration);
|
|
475
557
|
});
|
|
476
558
|
widget.update();
|
|
477
559
|
}, 30_000);
|
|
@@ -512,6 +594,344 @@ export default function (pi) {
|
|
|
512
594
|
usage,
|
|
513
595
|
};
|
|
514
596
|
}
|
|
597
|
+
// Durable completed reports. Bound lazily from the root session's plain
|
|
598
|
+
// metadata (cwd/id/file) and never from a captured ExtensionContext: async
|
|
599
|
+
// filesystem continuations outlive the context that started them.
|
|
600
|
+
/**
|
|
601
|
+
* Default session roots plus the root session file's own directory. The SDK
|
|
602
|
+
* allows a custom sessionDir beyond PI_CODING_AGENT_SESSION_DIR/<agentDir>/
|
|
603
|
+
* sessions; including it lets legacy raw reads/cleanup validation resolve the
|
|
604
|
+
* real parent file. Later session switches to a DIFFERENT custom dir are a
|
|
605
|
+
* known bounded gap of this single-store binding (T3 cleanup must recheck).
|
|
606
|
+
*/
|
|
607
|
+
function createReportStore(extraSessionRoots = []) {
|
|
608
|
+
const roots = new Set();
|
|
609
|
+
const envDir = process.env.PI_CODING_AGENT_SESSION_DIR?.trim();
|
|
610
|
+
if (envDir)
|
|
611
|
+
roots.add(resolve(envDir));
|
|
612
|
+
roots.add(resolve(join(getAgentDir(), "sessions")));
|
|
613
|
+
for (const root of extraSessionRoots)
|
|
614
|
+
roots.add(resolve(root));
|
|
615
|
+
return new ReportStore({ sessionRoots: [...roots] });
|
|
616
|
+
}
|
|
617
|
+
/** One live store per root; inactive roots are retired after their writes drain. */
|
|
618
|
+
const reportStores = new Map();
|
|
619
|
+
const reportActiveRoots = new Set();
|
|
620
|
+
let reportStore = createReportStore();
|
|
621
|
+
let reportBoundRoot;
|
|
622
|
+
let reportBindChain = Promise.resolve();
|
|
623
|
+
/**
|
|
624
|
+
* Settled generations that occurred before the first bind (harnesses without
|
|
625
|
+
* session_start). Plain clones only — never a live record/session — and one
|
|
626
|
+
* entry per id, since only the latest generation is a durable report.
|
|
627
|
+
*/
|
|
628
|
+
const pendingArchivedRecords = new Map();
|
|
629
|
+
const archiveRetryAttempts = new Map();
|
|
630
|
+
let archiveDrainTimer;
|
|
631
|
+
const MAX_ARCHIVE_RETRIES = 5;
|
|
632
|
+
let sessionEpoch = 0;
|
|
633
|
+
let shuttingDown = false;
|
|
634
|
+
let cleanupOperation;
|
|
635
|
+
/**
|
|
636
|
+
* Per-root read-invalidation counter. Bumped when a cleanup operation takes
|
|
637
|
+
* ownership of a root, and again when it releases it — never pruned, because
|
|
638
|
+
* the counter's only job is to differ between two points in time. An archived
|
|
639
|
+
* read that resumes across either edge re-resolves instead of returning the
|
|
640
|
+
* body it captured before the root changed.
|
|
641
|
+
*/
|
|
642
|
+
const cleanupReadInvalidations = new Map();
|
|
643
|
+
/**
|
|
644
|
+
* Selected reports whose durable deletion receipt may already be committed but
|
|
645
|
+
* could not be read back. `writeDeletionReceipt` publishes the receipt before
|
|
646
|
+
* it bumps the root generation, so a rejected call is NOT proof that the body
|
|
647
|
+
* survived — and an unreadable entry is not proof either. Such an id is a
|
|
648
|
+
* reported FAILURE (never a deletion), and the in-memory live body must not
|
|
649
|
+
* then be served as if the durable entry were still intact: that is handing
|
|
650
|
+
* back a report this command deleted. Ids only — no bodies, no paths — dropped
|
|
651
|
+
* when a new generation of that agent starts or when the session ends.
|
|
652
|
+
*/
|
|
653
|
+
const cleanupUnprovenReports = new Set();
|
|
654
|
+
const workflowCleanupProofs = new Map();
|
|
655
|
+
const workflowArtifactStores = new Map();
|
|
656
|
+
const discardedWorkflowNotifications = new Set();
|
|
657
|
+
/**
|
|
658
|
+
* Copy every plain field a report snapshot needs, synchronously, so a later
|
|
659
|
+
* resume cannot rewrite the generation being archived. Live SDK handles are
|
|
660
|
+
* deliberately excluded; the snapshot only needs `session.sessionId`.
|
|
661
|
+
*/
|
|
662
|
+
function cloneRecordForArchive(record) {
|
|
663
|
+
const sessionId = record.session?.sessionId ?? record.sessionId;
|
|
664
|
+
return {
|
|
665
|
+
id: record.id,
|
|
666
|
+
type: record.type,
|
|
667
|
+
description: record.description,
|
|
668
|
+
status: record.status,
|
|
669
|
+
...(record.result === undefined ? {} : { result: record.result }),
|
|
670
|
+
...(record.error === undefined ? {} : { error: record.error }),
|
|
671
|
+
toolUses: record.toolUses,
|
|
672
|
+
startedAt: record.startedAt,
|
|
673
|
+
...(record.completedAt === undefined ? {} : { completedAt: record.completedAt }),
|
|
674
|
+
...(sessionId === undefined
|
|
675
|
+
? {}
|
|
676
|
+
: { sessionId }),
|
|
677
|
+
...(record.sessionFile === undefined ? {} : { sessionFile: record.sessionFile }),
|
|
678
|
+
...(record.outputFile === undefined ? {} : { outputFile: record.outputFile }),
|
|
679
|
+
...(record.invocation === undefined ? {} : { invocation: { ...record.invocation } }),
|
|
680
|
+
lifetimeUsage: { ...record.lifetimeUsage },
|
|
681
|
+
compactionCount: record.compactionCount,
|
|
682
|
+
...(record.isBackground === undefined ? {} : { isBackground: record.isBackground }),
|
|
683
|
+
...(record.depth === undefined ? {} : { depth: record.depth }),
|
|
684
|
+
...(record.handle === undefined ? {} : { handle: record.handle }),
|
|
685
|
+
...(record.alias === undefined ? {} : { alias: record.alias }),
|
|
686
|
+
...(record.groupId === undefined ? {} : { groupId: record.groupId }),
|
|
687
|
+
...(record.runGeneration === undefined ? {} : { runGeneration: record.runGeneration }),
|
|
688
|
+
...(record.structuredJson === undefined ? {} : { structuredJson: record.structuredJson }),
|
|
689
|
+
...(record.structuredRetried === undefined ? {} : { structuredRetried: record.structuredRetried }),
|
|
690
|
+
...(record.droppedSteers === undefined ? {} : { droppedSteers: record.droppedSteers }),
|
|
691
|
+
...(record.resultConsumed === undefined ? {} : { resultConsumed: record.resultConsumed }),
|
|
692
|
+
...(record.parentAgentId === undefined ? {} : { parentAgentId: record.parentAgentId }),
|
|
693
|
+
...(record.workflowId === undefined ? {} : { workflowId: record.workflowId }),
|
|
694
|
+
...(record.ownerIds === undefined ? {} : { ownerIds: [...record.ownerIds] }),
|
|
695
|
+
...(record.rootSessionId === undefined ? {} : { rootSessionId: record.rootSessionId }),
|
|
696
|
+
...(record.rootCwd === undefined ? {} : { rootCwd: record.rootCwd }),
|
|
697
|
+
...(record.rootSessionFile === undefined ? {} : { rootSessionFile: record.rootSessionFile }),
|
|
698
|
+
...(record.pendingSteers === undefined ? {} : { pendingSteers: [...record.pendingSteers] }),
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
/** The store already bound for a record's own root, if that root has one. */
|
|
702
|
+
function storeForRecord(record) {
|
|
703
|
+
if (record.rootSessionId !== undefined)
|
|
704
|
+
return reportStores.get(record.rootSessionId);
|
|
705
|
+
return reportBoundRoot === undefined ? undefined : reportStore;
|
|
706
|
+
}
|
|
707
|
+
function saveArchivedRecord(record) {
|
|
708
|
+
const target = storeForRecord(record);
|
|
709
|
+
if (target === undefined) {
|
|
710
|
+
pendingArchivedRecords.set(record.id, cloneRecordForArchive(record));
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
const saving = target.save(record);
|
|
714
|
+
void saving.then((result) => {
|
|
715
|
+
// A saved FULL entry (which `save` only writes when no deletion receipt is
|
|
716
|
+
// present) is the one durable proof that replaces an unprovable receipt.
|
|
717
|
+
// Starting/resuming a run is not proof: `save` refuses to overwrite the
|
|
718
|
+
// receipt on its own, so the id stays refused until this lands.
|
|
719
|
+
if (result.saved === true) {
|
|
720
|
+
archiveRetryAttempts.delete(record.id);
|
|
721
|
+
cleanupUnprovenReports.delete(record.id);
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
const transient = result.reason === "cleanup-lock" || result.reason === "cleanup-lock-unreadable"
|
|
725
|
+
|| result.reason === "store-closed" || result.reason === "not-bound";
|
|
726
|
+
if (transient) {
|
|
727
|
+
// The pending archive must not be dropped just because the store that
|
|
728
|
+
// accepted the drain later refused a save. Keep the record queued for
|
|
729
|
+
// the next binding/retry while the reason is transient.
|
|
730
|
+
pendingArchivedRecords.set(record.id, cloneRecordForArchive(record));
|
|
731
|
+
schedulePendingArchiveDrain(record.id);
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
archiveRetryAttempts.delete(record.id);
|
|
735
|
+
if (result.reason !== "persist-disabled") {
|
|
736
|
+
console.warn(`[pi-subagents] durable report save refused for ${record.id}: ${result.reason}`);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}).catch((error) => {
|
|
740
|
+
console.warn("[pi-subagents] durable report save failed:", error);
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
function drainPendingArchivedRecords() {
|
|
744
|
+
const pending = [...pendingArchivedRecords.values()];
|
|
745
|
+
pendingArchivedRecords.clear();
|
|
746
|
+
for (const record of pending)
|
|
747
|
+
saveArchivedRecord(record);
|
|
748
|
+
}
|
|
749
|
+
function schedulePendingArchiveDrain(recordId) {
|
|
750
|
+
const attempts = archiveRetryAttempts.get(recordId) ?? 0;
|
|
751
|
+
if (attempts >= MAX_ARCHIVE_RETRIES) {
|
|
752
|
+
console.warn(`[pi-subagents] durable report retry limit reached for ${recordId}`);
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
archiveRetryAttempts.set(recordId, attempts + 1);
|
|
756
|
+
if (archiveDrainTimer !== undefined)
|
|
757
|
+
return;
|
|
758
|
+
const delay = Math.min(100 * 2 ** Math.max(0, attempts - 1), 1000);
|
|
759
|
+
archiveDrainTimer = setTimeout(() => {
|
|
760
|
+
archiveDrainTimer = undefined;
|
|
761
|
+
drainPendingArchivedRecords();
|
|
762
|
+
}, delay);
|
|
763
|
+
archiveDrainTimer.unref?.();
|
|
764
|
+
}
|
|
765
|
+
function reportContextFor(ctx) {
|
|
766
|
+
const rootSessionId = ctx.sessionManager?.getSessionId?.();
|
|
767
|
+
if (!rootSessionId)
|
|
768
|
+
return undefined;
|
|
769
|
+
const rootSessionFile = ctx.sessionManager?.getSessionFile?.();
|
|
770
|
+
return {
|
|
771
|
+
cwd: ctx.cwd,
|
|
772
|
+
rootSessionId,
|
|
773
|
+
...(rootSessionFile === undefined ? {} : { rootSessionFile }),
|
|
774
|
+
persistReports: rootSessionFile !== undefined,
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
/** A root with live/finalizing work keeps its store until a later boundary. */
|
|
778
|
+
function reportRootHasLiveWork(rootSessionId) {
|
|
779
|
+
if (manager.listAgents().some(record => (record.rootSessionId ?? reportBoundRoot) === rootSessionId))
|
|
780
|
+
return true;
|
|
781
|
+
for (const [id, task] of workflowTasks) {
|
|
782
|
+
if (workflowArtifactRoots.get(id) !== rootSessionId)
|
|
783
|
+
continue;
|
|
784
|
+
if (task.status === "running" || task.status === "paused"
|
|
785
|
+
|| workflowRunPromises.has(id) || workflowJournalDrains.has(id))
|
|
786
|
+
return true;
|
|
787
|
+
}
|
|
788
|
+
return false;
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Close together so every store stops write admission before any await. An
|
|
792
|
+
* incomplete close is explicit and retains that store's lease; it is never
|
|
793
|
+
* logged or treated as a successful durable drain.
|
|
794
|
+
*/
|
|
795
|
+
async function closeReportStores(stores, quiescent) {
|
|
796
|
+
await Promise.all([...stores].map(async (store) => {
|
|
797
|
+
try {
|
|
798
|
+
const drained = await store.close({ quiescent });
|
|
799
|
+
if (drained.status !== "flushed") {
|
|
800
|
+
console.warn(`[pi-subagents] durable report flush incomplete (${drained.reason}); lease retained`);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
catch (error) {
|
|
804
|
+
console.warn("[pi-subagents] durable report close failed:", error);
|
|
805
|
+
}
|
|
806
|
+
}));
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Replacement prunes only roots with no live records/runs. Their accepted
|
|
810
|
+
* writes and maintenance drain inside close; roots still producing reports
|
|
811
|
+
* keep the exact store pinned to that work.
|
|
812
|
+
*/
|
|
813
|
+
async function pruneReportStores(nextRoot) {
|
|
814
|
+
drainPendingArchivedRecords();
|
|
815
|
+
const candidates = [...reportStores.entries()].filter(([root]) => root !== nextRoot && !reportRootHasLiveWork(root));
|
|
816
|
+
if (candidates.length === 0)
|
|
817
|
+
return;
|
|
818
|
+
const retired = new Set(candidates.map(([, store]) => store));
|
|
819
|
+
if (candidates.some(([root]) => root === reportBoundRoot))
|
|
820
|
+
reportBoundRoot = undefined;
|
|
821
|
+
await closeReportStores(retired, true);
|
|
822
|
+
for (const [root, store] of candidates) {
|
|
823
|
+
if (reportStores.get(root) === store)
|
|
824
|
+
reportStores.delete(root);
|
|
825
|
+
reportActiveRoots.delete(root);
|
|
826
|
+
}
|
|
827
|
+
for (const [id, store] of workflowArtifactStores) {
|
|
828
|
+
if (retired.has(store))
|
|
829
|
+
workflowArtifactStores.delete(id);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Bind the store to the current ROOT session, lazily for callers that enter
|
|
834
|
+
* without a `session_start` (tests, RPC-only harnesses). Serialized so a
|
|
835
|
+
* late bind can never overwrite a newer root's binding, and plain-data only.
|
|
836
|
+
*/
|
|
837
|
+
function ensureReportBinding(ctx) {
|
|
838
|
+
const context = reportContextFor(ctx);
|
|
839
|
+
if (!context)
|
|
840
|
+
return Promise.resolve();
|
|
841
|
+
if (reportBoundRoot === context.rootSessionId && reportActiveRoots.has(context.rootSessionId))
|
|
842
|
+
return Promise.resolve();
|
|
843
|
+
const next = reportBindChain
|
|
844
|
+
.then(async () => {
|
|
845
|
+
if (reportBoundRoot === context.rootSessionId && reportActiveRoots.has(context.rootSessionId))
|
|
846
|
+
return;
|
|
847
|
+
await pruneReportStores(context.rootSessionId);
|
|
848
|
+
let target = reportStores.get(context.rootSessionId);
|
|
849
|
+
if (target?.isClosed) {
|
|
850
|
+
// A closed/closing store is never a candidate for a new activation,
|
|
851
|
+
// even when the root id is reused by a later session.
|
|
852
|
+
reportStores.delete(context.rootSessionId);
|
|
853
|
+
reportActiveRoots.delete(context.rootSessionId);
|
|
854
|
+
target = undefined;
|
|
855
|
+
}
|
|
856
|
+
if (target === undefined) {
|
|
857
|
+
const extra = [];
|
|
858
|
+
if (context.rootSessionFile !== undefined)
|
|
859
|
+
extra.push(dirname(context.rootSessionFile));
|
|
860
|
+
target = createReportStore(extra);
|
|
861
|
+
}
|
|
862
|
+
else if (reportActiveRoots.has(context.rootSessionId)) {
|
|
863
|
+
// Switching back to a still-bound root: keep its lease/context.
|
|
864
|
+
reportStore = target;
|
|
865
|
+
reportBoundRoot = context.rootSessionId;
|
|
866
|
+
drainPendingArchivedRecords();
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
const binding = await target.bind(context);
|
|
870
|
+
if (binding.active)
|
|
871
|
+
reportActiveRoots.add(context.rootSessionId);
|
|
872
|
+
else {
|
|
873
|
+
reportActiveRoots.delete(context.rootSessionId);
|
|
874
|
+
console.warn(`[pi-subagents] durable report binding refused for ${context.rootSessionId}: ${binding.reason}`);
|
|
875
|
+
}
|
|
876
|
+
reportStores.set(context.rootSessionId, target);
|
|
877
|
+
reportStore = target;
|
|
878
|
+
// An inactive store still supports reads, but the next operation retries
|
|
879
|
+
// activation: a transient cleanup lock must not strand this root forever.
|
|
880
|
+
reportBoundRoot = context.rootSessionId;
|
|
881
|
+
drainPendingArchivedRecords();
|
|
882
|
+
})
|
|
883
|
+
.catch((error) => {
|
|
884
|
+
console.warn("[pi-subagents] durable report store unavailable:", error);
|
|
885
|
+
});
|
|
886
|
+
reportBindChain = next;
|
|
887
|
+
return next;
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Await a root's own binding admission before an Agent run may create a
|
|
891
|
+
* session, transcript or worktree.
|
|
892
|
+
*
|
|
893
|
+
* A supported SDK host can create a session and call `prompt()` without
|
|
894
|
+
* `bindExtensions()` (installed docs/sdk.md and examples/sdk/06-extensions.ts),
|
|
895
|
+
* so `session_start` — the only startup bind — never fires. The lazy bind the
|
|
896
|
+
* tool starts is then the FIRST activation of that root, and an absent store
|
|
897
|
+
* is not permission to spawn: a cleanup lock or a refused activation must be
|
|
898
|
+
* seen before the first artifact exists. `reportBindChain` already serializes
|
|
899
|
+
* that bind, so awaiting it adds nothing but the proof.
|
|
900
|
+
*
|
|
901
|
+
* An already-active root returns without yielding, preserving the same-tick
|
|
902
|
+
* foreground batch; an intentionally ephemeral context keeps its historical
|
|
903
|
+
* synchronous deferred-bind contract.
|
|
904
|
+
*/
|
|
905
|
+
function reportBindingAdmission(ctx) {
|
|
906
|
+
const context = reportContextFor(ctx);
|
|
907
|
+
if (context === undefined || context.persistReports !== true)
|
|
908
|
+
return undefined;
|
|
909
|
+
const root = context.rootSessionId;
|
|
910
|
+
// Already active / intentional ephemeral / reserved: no promise at all, so
|
|
911
|
+
// the caller does not even yield a microtask (same-tick batch + no widened
|
|
912
|
+
// window against a transient maintenance lock).
|
|
913
|
+
if (reportActiveRoots.has(root))
|
|
914
|
+
return undefined;
|
|
915
|
+
// A root this operation is about to delete is never bound: binding publishes
|
|
916
|
+
// a lease and runs maintenance. The acquisition guard below refuses it.
|
|
917
|
+
if (cleanupRootReserved(root))
|
|
918
|
+
return undefined;
|
|
919
|
+
return ensureReportBinding(ctx);
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Synchronous half of the same boundary for entry points that cannot await
|
|
923
|
+
* (the cross-package registry and the bus RPC handlers, both synchronous by
|
|
924
|
+
* contract). A persistent root with no proven-active store refuses before a
|
|
925
|
+
* new id or SDK history exists; an ephemeral context keeps its behavior.
|
|
926
|
+
*/
|
|
927
|
+
function assertReportBindingAdmission(ctx) {
|
|
928
|
+
const context = reportContextFor(ctx);
|
|
929
|
+
if (context === undefined || context.persistReports !== true)
|
|
930
|
+
return;
|
|
931
|
+
if (reportActiveRoots.has(context.rootSessionId))
|
|
932
|
+
return;
|
|
933
|
+
throw new ReportUnavailableError("report-binding-not-active");
|
|
934
|
+
}
|
|
515
935
|
// Background completion: route through group join or send individual nudge
|
|
516
936
|
const manager = new AgentManager((record) => {
|
|
517
937
|
// Every settle changes whether subagent work remains, which is what the
|
|
@@ -543,7 +963,6 @@ export default function (pi) {
|
|
|
543
963
|
if (record.resultConsumed) {
|
|
544
964
|
agentActivity.delete(record.id);
|
|
545
965
|
widget.markFinished(record.id);
|
|
546
|
-
fleet.onAgentFinished(record.id);
|
|
547
966
|
widget.update();
|
|
548
967
|
return;
|
|
549
968
|
}
|
|
@@ -571,35 +990,1080 @@ export default function (pi) {
|
|
|
571
990
|
if (currentCtx?.hasUI) {
|
|
572
991
|
widget.ensureTimer();
|
|
573
992
|
widget.update();
|
|
574
|
-
fleet.ensureTimer();
|
|
575
|
-
fleet.update();
|
|
576
993
|
}
|
|
577
|
-
// Emit started event when agent transitions to running (including from queue)
|
|
578
|
-
pi.events.emit("subagents:started", {
|
|
579
|
-
id: record.id,
|
|
580
|
-
type: record.type,
|
|
581
|
-
description: record.description,
|
|
582
|
-
});
|
|
583
|
-
}, (record, info) => {
|
|
584
|
-
if (!isTopLevelAgent(record))
|
|
994
|
+
// Emit started event when agent transitions to running (including from queue)
|
|
995
|
+
pi.events.emit("subagents:started", {
|
|
996
|
+
id: record.id,
|
|
997
|
+
type: record.type,
|
|
998
|
+
description: record.description,
|
|
999
|
+
});
|
|
1000
|
+
}, (record, info) => {
|
|
1001
|
+
if (!isTopLevelAgent(record))
|
|
1002
|
+
return;
|
|
1003
|
+
// Emit compacted event when agent's session compacts (preserves count on record).
|
|
1004
|
+
pi.events.emit("subagents:compacted", {
|
|
1005
|
+
id: record.id,
|
|
1006
|
+
type: record.type,
|
|
1007
|
+
description: record.description,
|
|
1008
|
+
reason: info.reason,
|
|
1009
|
+
tokensBefore: info.tokensBefore,
|
|
1010
|
+
compactionCount: record.compactionCount,
|
|
1011
|
+
});
|
|
1012
|
+
}, (_record, usage) => {
|
|
1013
|
+
// Every assistant message from every agent — nested included, exactly once.
|
|
1014
|
+
// Parked here until a tool result can carry it back to the parent session;
|
|
1015
|
+
// see `PendingUsagePool`. Skipped entirely when the feature is off, so no
|
|
1016
|
+
// pool grows in a session that will never drain it.
|
|
1017
|
+
if (reportUsage)
|
|
1018
|
+
pendingUsage.add(usage);
|
|
1019
|
+
});
|
|
1020
|
+
// Every terminal generation reaches the archiver, including the foreground
|
|
1021
|
+
// resumes and queued stops that never call onComplete.
|
|
1022
|
+
manager.setReportArchiver({ save: record => saveArchivedRecord(record) });
|
|
1023
|
+
// Acquire-side cleanup barrier: reserved roots and selected ids/paths refuse
|
|
1024
|
+
// new artifact work before a session, output or worktree is written.
|
|
1025
|
+
manager.setArtifactAccessGuard(record => assertCleanupArtifactAccessAsync(record));
|
|
1026
|
+
// Injected into nested tools via the runner so an owner can read its own
|
|
1027
|
+
// archived child after eviction; `findOwned` enforces exact parentAgentId.
|
|
1028
|
+
manager.setArchivedReportReader({
|
|
1029
|
+
findOwned: async (ref, owner) => {
|
|
1030
|
+
// A live record can be evicted in the same tick its snapshot was queued;
|
|
1031
|
+
// flush before the durable read so it observes its own completed write.
|
|
1032
|
+
const parent = manager.getRecord(owner.id);
|
|
1033
|
+
const target = (parent === undefined ? undefined : storeForRecord(parent)) ?? reportStore;
|
|
1034
|
+
const ownerRoot = parent?.rootSessionId;
|
|
1035
|
+
// The lookup below re-reads the durable entry after every await, so it is
|
|
1036
|
+
// never a cached body. The token only has to catch a cleanup that took or
|
|
1037
|
+
// released the owner's root while this call was in flight.
|
|
1038
|
+
const token = cleanupReadTokenFor(ownerRoot);
|
|
1039
|
+
const drained = await target.flush();
|
|
1040
|
+
if (drained.status !== "flushed") {
|
|
1041
|
+
return { status: "missing", ref, reason: `report-writes-not-flushed:${drained.reason}` };
|
|
1042
|
+
}
|
|
1043
|
+
const lookup = await target.findOwned(ref, owner.id, owner);
|
|
1044
|
+
if (lookup.status === "found") {
|
|
1045
|
+
const refusal = cleanupReadRefusal({
|
|
1046
|
+
agentId: lookup.report.id,
|
|
1047
|
+
sessionFile: lookup.report.sessionFile,
|
|
1048
|
+
rootSessionId: lookup.report.rootSessionId,
|
|
1049
|
+
});
|
|
1050
|
+
if (refusal !== undefined) {
|
|
1051
|
+
return { status: "missing", ref, reason: refusal };
|
|
1052
|
+
}
|
|
1053
|
+
if (cleanupReadTokenFor(ownerRoot) !== token) {
|
|
1054
|
+
return { status: "missing", ref, reason: "cleanup-changed-owner-root" };
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
return lookup;
|
|
1058
|
+
},
|
|
1059
|
+
});
|
|
1060
|
+
function parseCleanupArgs(tokens) {
|
|
1061
|
+
let scope = "session";
|
|
1062
|
+
let scopeSeen = false;
|
|
1063
|
+
let dryRun = false;
|
|
1064
|
+
let includeLegacy = false;
|
|
1065
|
+
for (const raw of tokens) {
|
|
1066
|
+
const token = raw.toLowerCase();
|
|
1067
|
+
if (token === "session" || token === "global") {
|
|
1068
|
+
if (scopeSeen)
|
|
1069
|
+
return undefined;
|
|
1070
|
+
scope = token;
|
|
1071
|
+
scopeSeen = true;
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
if (token === "--dry-run") {
|
|
1075
|
+
if (dryRun)
|
|
1076
|
+
return undefined;
|
|
1077
|
+
dryRun = true;
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
if (token === "--include-legacy") {
|
|
1081
|
+
if (includeLegacy)
|
|
1082
|
+
return undefined;
|
|
1083
|
+
includeLegacy = true;
|
|
1084
|
+
continue;
|
|
1085
|
+
}
|
|
1086
|
+
// Includes on/off, --yes/-y/--force and any unknown flag: cleanup never
|
|
1087
|
+
// toggles or bypasses its explicit confirmation.
|
|
1088
|
+
return undefined;
|
|
1089
|
+
}
|
|
1090
|
+
return { scope, dryRun, includeLegacy };
|
|
1091
|
+
}
|
|
1092
|
+
function cleanupUsage() {
|
|
1093
|
+
return "Usage: /subagents cleanup [session|global] [--dry-run] [--include-legacy] — nothing is deleted without an explicit preview and confirmation. Use /subagents on|off for the model policy toggle.";
|
|
1094
|
+
}
|
|
1095
|
+
function safeCleanupText(value) {
|
|
1096
|
+
// JSON escaping covers quotes, backslashes and C0; C1/DEL are not escaped by
|
|
1097
|
+
// JSON.stringify and are the remaining terminal-control injection surface.
|
|
1098
|
+
return JSON.stringify(value).replace(/[\u007f-\u009f]/g, ch => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
1099
|
+
}
|
|
1100
|
+
function cleanupOperationCurrent(op) {
|
|
1101
|
+
return op.epoch === sessionEpoch && op.readRoot() === op.rootSessionId;
|
|
1102
|
+
}
|
|
1103
|
+
function cleanupPathKey(path) {
|
|
1104
|
+
return normalizeReportPath(path);
|
|
1105
|
+
}
|
|
1106
|
+
function cleanupSelectionPaths(...paths) {
|
|
1107
|
+
return paths.filter((path) => path !== undefined).map(cleanupPathKey);
|
|
1108
|
+
}
|
|
1109
|
+
/** The store that actually owns this root — i.e. one whose bind was attempted. */
|
|
1110
|
+
function owningReportStore(rootSessionId) {
|
|
1111
|
+
if (rootSessionId === undefined)
|
|
1112
|
+
return undefined;
|
|
1113
|
+
const store = reportStores.get(rootSessionId);
|
|
1114
|
+
return store?.bindingContext?.rootSessionId === rootSessionId ? store : undefined;
|
|
1115
|
+
}
|
|
1116
|
+
/** Whether this command has an operation that is about to delete this root. */
|
|
1117
|
+
function cleanupRootReserved(rootSessionId) {
|
|
1118
|
+
const op = cleanupOperation;
|
|
1119
|
+
return rootSessionId !== undefined
|
|
1120
|
+
&& op !== undefined
|
|
1121
|
+
&& cleanupOperationCurrent(op)
|
|
1122
|
+
&& op.reservedRoots.has(rootSessionId);
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* Whether a planned id is still operation-LOCALLY selected. The answer is
|
|
1126
|
+
* deliberately conditioned on the entry's root still being reserved: a root
|
|
1127
|
+
* that froze as busy or whose generation was superseded keeps its work, so it
|
|
1128
|
+
* must not carry an id/path barrier cleanup will never act on. Real store
|
|
1129
|
+
* locks are enforced separately and always.
|
|
1130
|
+
*/
|
|
1131
|
+
function cleanupAgentSelected(op, agentId) {
|
|
1132
|
+
const root = op.planAgentRoots.get(agentId);
|
|
1133
|
+
return root !== undefined && op.reservedRoots.has(root);
|
|
1134
|
+
}
|
|
1135
|
+
function cleanupPathSelected(op, path) {
|
|
1136
|
+
const root = op.planPathRoots.get(path);
|
|
1137
|
+
return root !== undefined && op.reservedRoots.has(root);
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Index-local reservations, re-run synchronously after the last store I/O.
|
|
1141
|
+
* A cleanup command's selection is command-local state, not filesystem truth:
|
|
1142
|
+
* it must be checked in the same tick as the admission it protects, or a
|
|
1143
|
+
* cleanup that began while an async guard was suspended could slip through.
|
|
1144
|
+
*/
|
|
1145
|
+
function assertCleanupLocalAccess(rootSessionId, paths, agentId) {
|
|
1146
|
+
const op = cleanupOperation;
|
|
1147
|
+
if (op === undefined || !cleanupOperationCurrent(op))
|
|
1148
|
+
return;
|
|
1149
|
+
for (const path of cleanupSelectionPaths(...paths)) {
|
|
1150
|
+
if (cleanupPathSelected(op, path))
|
|
1151
|
+
throw new ReportUnavailableError("cleanup-selected-path");
|
|
1152
|
+
}
|
|
1153
|
+
if (agentId !== undefined && cleanupAgentSelected(op, agentId)) {
|
|
1154
|
+
throw new ReportUnavailableError("cleanup-selected-agent");
|
|
1155
|
+
}
|
|
1156
|
+
if (rootSessionId === undefined)
|
|
1157
|
+
throw new ReportUnavailableError("cleanup-unknown-root");
|
|
1158
|
+
if (op.reservedRoots.has(rootSessionId))
|
|
1159
|
+
throw new ReportUnavailableError("cleanup-reserved-root");
|
|
1160
|
+
}
|
|
1161
|
+
/**
|
|
1162
|
+
* Acquire-side barrier.
|
|
1163
|
+
*
|
|
1164
|
+
* The owning store's REAL activation/root availability is enforced
|
|
1165
|
+
* unconditionally: a valid foreign lock that was already held when this
|
|
1166
|
+
* activation first met the root leaves the store inactive, and "no local
|
|
1167
|
+
* cleanup operation" is not permission to start a session, transcript,
|
|
1168
|
+
* worktree or workflow on top of it. Only the command-local reservations and
|
|
1169
|
+
* selections are conditional, because they exist only while a command is
|
|
1170
|
+
* applying.
|
|
1171
|
+
*/
|
|
1172
|
+
function assertCleanupRootAccess(rootSessionId, paths = []) {
|
|
1173
|
+
const store = owningReportStore(rootSessionId);
|
|
1174
|
+
// Inactive activation, closed store, or a live/uncertain lock of its own
|
|
1175
|
+
// root. Reads deliberately do NOT come through here (see cleanupReadRefusal).
|
|
1176
|
+
store?.assertAvailable();
|
|
1177
|
+
assertCleanupLocalAccess(rootSessionId, paths);
|
|
1178
|
+
if (rootSessionId === undefined)
|
|
1179
|
+
return;
|
|
1180
|
+
// Canonical selection of exactly these artifacts by any lock, local or
|
|
1181
|
+
// foreign, is enforced even with no operation of ours running. One combined
|
|
1182
|
+
// scan, not one full listing per path.
|
|
1183
|
+
const scan = store ?? reportStore;
|
|
1184
|
+
const sessionFiles = cleanupSelectionPaths(...paths);
|
|
1185
|
+
if (sessionFiles.length > 0)
|
|
1186
|
+
scan.assertAvailableAny({ sessionFiles });
|
|
1187
|
+
}
|
|
1188
|
+
/**
|
|
1189
|
+
* Awaitable twin of {@link assertCleanupRootAccess} for paths that have
|
|
1190
|
+
* already suspended. Store I/O comes first; the command-local reservations
|
|
1191
|
+
* are re-checked synchronously afterwards, so no await sits between that
|
|
1192
|
+
* final check and admission.
|
|
1193
|
+
*/
|
|
1194
|
+
async function assertCleanupRootAccessAsync(rootSessionId, paths = []) {
|
|
1195
|
+
const store = owningReportStore(rootSessionId);
|
|
1196
|
+
if (store !== undefined)
|
|
1197
|
+
await store.assertAvailableAsync();
|
|
1198
|
+
if (rootSessionId !== undefined) {
|
|
1199
|
+
const scan = store ?? reportStore;
|
|
1200
|
+
const sessionFiles = cleanupSelectionPaths(...paths);
|
|
1201
|
+
if (sessionFiles.length > 0)
|
|
1202
|
+
await scan.assertAvailableAnyAsync({ sessionFiles });
|
|
1203
|
+
}
|
|
1204
|
+
// LAST: no await after the local reservation check.
|
|
1205
|
+
assertCleanupLocalAccess(rootSessionId, paths);
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Awaitable artifact barrier for the manager's acquire-side guard and for
|
|
1209
|
+
* resume paths. One combined async scan covers the agent id, its session and
|
|
1210
|
+
* its transcript; the index-local reservations are re-checked last.
|
|
1211
|
+
*/
|
|
1212
|
+
async function assertCleanupArtifactAccessAsync(record) {
|
|
1213
|
+
// An unproven deletion receipt is an ids-only barrier that outlives its
|
|
1214
|
+
// operation: a live resume keeps this agent's id, so it must not reopen
|
|
1215
|
+
// work or write a transcript over a body cleanup may already have removed.
|
|
1216
|
+
if (cleanupUnprovenReports.has(record.id))
|
|
1217
|
+
throw new ReportUnavailableError("cleanup-receipt-unproven");
|
|
1218
|
+
const owning = owningReportStore(record.rootSessionId);
|
|
1219
|
+
if (owning !== undefined)
|
|
1220
|
+
await owning.assertAvailableAsync();
|
|
1221
|
+
const store = (record.rootSessionId === undefined ? undefined : reportStores.get(record.rootSessionId)) ?? reportStore;
|
|
1222
|
+
await store.assertAvailableAnyAsync({
|
|
1223
|
+
agentId: record.id,
|
|
1224
|
+
sessionFiles: cleanupSelectionPaths(record.sessionFile, record.outputFile),
|
|
1225
|
+
});
|
|
1226
|
+
// LAST: no await after the local reservation check.
|
|
1227
|
+
assertCleanupLocalAccess(record.rootSessionId, [record.sessionFile, record.outputFile], record.id);
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Why an exact report/session read must not continue, or undefined.
|
|
1231
|
+
*
|
|
1232
|
+
* Cleanup state is consulted when an operation is applying (and only for the
|
|
1233
|
+
* roots it actually reserved); the store's own lock view is consulted ALWAYS,
|
|
1234
|
+
* so a foreign cleanup deleting this exact agent/session is refused even
|
|
1235
|
+
* though this process never ran the command.
|
|
1236
|
+
*/
|
|
1237
|
+
function cleanupReadRefusal(ref) {
|
|
1238
|
+
// Unprovable receipt state outlives the operation: the barrier is gone, but
|
|
1239
|
+
// the durable entry may already be a deletion receipt.
|
|
1240
|
+
if (ref.agentId !== undefined && cleanupUnprovenReports.has(ref.agentId))
|
|
1241
|
+
return "cleanup-receipt-unproven";
|
|
1242
|
+
const op = cleanupOperation;
|
|
1243
|
+
if (op !== undefined && cleanupOperationCurrent(op)) {
|
|
1244
|
+
if (ref.agentId !== undefined && cleanupAgentSelected(op, ref.agentId))
|
|
1245
|
+
return "cleanup-in-progress";
|
|
1246
|
+
const paths = cleanupSelectionPaths(ref.sessionFile, ref.path);
|
|
1247
|
+
if (paths.some(path => cleanupPathSelected(op, path)))
|
|
1248
|
+
return "cleanup-in-progress";
|
|
1249
|
+
}
|
|
1250
|
+
const store = (ref.rootSessionId === undefined ? undefined : reportStores.get(ref.rootSessionId)) ?? reportStore;
|
|
1251
|
+
try {
|
|
1252
|
+
store.assertAvailable(ref.agentId, ref.sessionFile);
|
|
1253
|
+
}
|
|
1254
|
+
catch (error) {
|
|
1255
|
+
if (error instanceof ReportUnavailableError)
|
|
1256
|
+
return `cleanup-in-progress:${error.message}`;
|
|
1257
|
+
throw error;
|
|
1258
|
+
}
|
|
1259
|
+
return undefined;
|
|
1260
|
+
}
|
|
1261
|
+
function cleanupReadTokenFor(rootSessionId) {
|
|
1262
|
+
return rootSessionId === undefined ? 0 : (cleanupReadInvalidations.get(rootSessionId) ?? 0);
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Record every selected report whose receipt state cleanup could not prove.
|
|
1266
|
+
*
|
|
1267
|
+
* The backend answers a report candidate in exactly one of three ways: marked
|
|
1268
|
+
* deleted (a durable deleted entry was read back), failed with
|
|
1269
|
+
* `receipt-state-uncertain` (the entry could not be read at all), or failed
|
|
1270
|
+
* with `receipt-failed` (the mutator rejected and the entry did not read back
|
|
1271
|
+
* as a deletion — which includes the entry being absent/unparseable). The last
|
|
1272
|
+
* two cannot prove the body survived, so they fail closed here rather than
|
|
1273
|
+
* leaving the cached live report readable after the barrier is released.
|
|
1274
|
+
*/
|
|
1275
|
+
function markUnprovenCleanupReports(result) {
|
|
1276
|
+
for (const failure of result.failed) {
|
|
1277
|
+
if (failure.agentId === undefined || failure.kind !== "report-entry")
|
|
1278
|
+
continue;
|
|
1279
|
+
if (!failure.reason.startsWith("receipt-"))
|
|
1280
|
+
continue;
|
|
1281
|
+
if (result.deletedAgentIds.includes(failure.agentId))
|
|
1282
|
+
continue;
|
|
1283
|
+
cleanupUnprovenReports.add(failure.agentId);
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
/** Bump every root an operation will touch, at both edges of that operation. */
|
|
1287
|
+
function invalidateCleanupReads(roots) {
|
|
1288
|
+
for (const root of roots)
|
|
1289
|
+
cleanupReadInvalidations.set(root, cleanupReadTokenFor(root) + 1);
|
|
1290
|
+
}
|
|
1291
|
+
function addCleanupPaths(target, ...paths) {
|
|
1292
|
+
for (const path of paths) {
|
|
1293
|
+
if (path === undefined)
|
|
1294
|
+
continue;
|
|
1295
|
+
target.add(cleanupPathKey(path));
|
|
1296
|
+
let parent = dirname(path);
|
|
1297
|
+
while (parent.length > 1 && parent !== dirname(parent)) {
|
|
1298
|
+
target.add(cleanupPathKey(parent));
|
|
1299
|
+
parent = dirname(parent);
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
/** Synchronous runtime proof used by preview, reservations and every unlink gate. */
|
|
1304
|
+
function collectCleanupRuntime() {
|
|
1305
|
+
const activeAgentIds = new Set();
|
|
1306
|
+
const activeWorkflowIds = new Set();
|
|
1307
|
+
const protectedPaths = new Set();
|
|
1308
|
+
const unreadAgentIds = new Set();
|
|
1309
|
+
const protectedRoots = new Set();
|
|
1310
|
+
let unknownRootActivity = false;
|
|
1311
|
+
const addRoot = (rootSessionId) => {
|
|
1312
|
+
if (rootSessionId !== undefined && rootSessionId.length > 0)
|
|
1313
|
+
protectedRoots.add(rootSessionId);
|
|
1314
|
+
else
|
|
1315
|
+
unknownRootActivity = true;
|
|
1316
|
+
};
|
|
1317
|
+
const visited = new Set();
|
|
1318
|
+
const addRecord = (record) => {
|
|
1319
|
+
const stack = [record];
|
|
1320
|
+
while (stack.length > 0) {
|
|
1321
|
+
const current = stack.pop();
|
|
1322
|
+
if (current === undefined || visited.has(current))
|
|
1323
|
+
continue;
|
|
1324
|
+
visited.add(current);
|
|
1325
|
+
activeAgentIds.add(current.id);
|
|
1326
|
+
addRoot(current.rootSessionId);
|
|
1327
|
+
addCleanupPaths(protectedPaths, current.sessionFile, current.outputFile);
|
|
1328
|
+
for (const ownerId of current.ownerIds ?? []) {
|
|
1329
|
+
activeAgentIds.add(ownerId);
|
|
1330
|
+
const owner = manager.getRecord(ownerId);
|
|
1331
|
+
if (owner === undefined)
|
|
1332
|
+
unknownRootActivity = true;
|
|
1333
|
+
else
|
|
1334
|
+
stack.push(owner);
|
|
1335
|
+
}
|
|
1336
|
+
if (current.parentAgentId !== undefined) {
|
|
1337
|
+
activeAgentIds.add(current.parentAgentId);
|
|
1338
|
+
const parent = manager.getRecord(current.parentAgentId);
|
|
1339
|
+
if (parent === undefined)
|
|
1340
|
+
unknownRootActivity = true;
|
|
1341
|
+
else
|
|
1342
|
+
stack.push(parent);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
for (const id of manager.getBusyAgentIds()) {
|
|
1347
|
+
const record = manager.getRecord(id);
|
|
1348
|
+
if (record === undefined) {
|
|
1349
|
+
activeAgentIds.add(id);
|
|
1350
|
+
unknownRootActivity = true;
|
|
1351
|
+
}
|
|
1352
|
+
else {
|
|
1353
|
+
addRecord(record);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
for (const row of manager.listUncertainTeardowns()) {
|
|
1357
|
+
activeAgentIds.add(row.agentId);
|
|
1358
|
+
addRoot(row.rootSessionId);
|
|
1359
|
+
addCleanupPaths(protectedPaths, row.sessionFile, row.rootSessionFile);
|
|
1360
|
+
}
|
|
1361
|
+
for (const record of manager.listAgents()) {
|
|
1362
|
+
if (record.resultConsumed !== true)
|
|
1363
|
+
unreadAgentIds.add(record.id);
|
|
1364
|
+
}
|
|
1365
|
+
for (const task of workflowTasks.values()) {
|
|
1366
|
+
const proof = workflowCleanupProofs.get(task.id);
|
|
1367
|
+
const active = proof !== undefined || task.status === "running" || task.status === "paused";
|
|
1368
|
+
if (!active)
|
|
1369
|
+
continue;
|
|
1370
|
+
activeWorkflowIds.add(task.id);
|
|
1371
|
+
addRoot(proof?.rootSessionId ?? workflowArtifactRoots.get(task.id));
|
|
1372
|
+
const paths = workflowArtifactPaths.get(task.id);
|
|
1373
|
+
addCleanupPaths(protectedPaths, ...(paths?.generatedPaths ?? []), ...(paths?.externalPaths ?? []));
|
|
1374
|
+
addCleanupPaths(protectedPaths, ...(proof?.generatedPaths ?? []), ...(proof?.externalPaths ?? []));
|
|
1375
|
+
}
|
|
1376
|
+
for (const [id, proof] of workflowCleanupProofs) {
|
|
1377
|
+
activeWorkflowIds.add(id);
|
|
1378
|
+
addRoot(proof.rootSessionId);
|
|
1379
|
+
addCleanupPaths(protectedPaths, ...proof.generatedPaths, ...proof.externalPaths);
|
|
1380
|
+
}
|
|
1381
|
+
return {
|
|
1382
|
+
activeAgentIds,
|
|
1383
|
+
activeWorkflowIds,
|
|
1384
|
+
protectedPaths,
|
|
1385
|
+
unreadAgentIds,
|
|
1386
|
+
protectedRoots,
|
|
1387
|
+
unknownRootActivity,
|
|
1388
|
+
hasActiveWork: activeAgentIds.size > 0 || activeWorkflowIds.size > 0 || unknownRootActivity,
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
function cleanupLiveStateForRuntime(runtime, protectAllCandidates) {
|
|
1392
|
+
const protectedRoots = new Set(runtime.protectedRoots);
|
|
1393
|
+
if (runtime.unknownRootActivity) {
|
|
1394
|
+
for (const root of protectAllCandidates ?? [])
|
|
1395
|
+
protectedRoots.add(root);
|
|
1396
|
+
}
|
|
1397
|
+
return {
|
|
1398
|
+
activeAgentIds: runtime.activeAgentIds,
|
|
1399
|
+
activeWorkflowIds: runtime.activeWorkflowIds,
|
|
1400
|
+
protectedPaths: runtime.protectedPaths,
|
|
1401
|
+
unreadAgentIds: runtime.unreadAgentIds,
|
|
1402
|
+
diagnosticsBusy: runtime.hasActiveWork,
|
|
1403
|
+
protectedRootSessionIds: protectedRoots,
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
/** Build the preview without ever acquiring a cleanup lock or touching a file. */
|
|
1407
|
+
async function buildCleanupPreviewPlan(baseStore, scope, includeLegacy, runtime, stores, previewRootSessionId) {
|
|
1408
|
+
const build = async (protectAllCandidates) => {
|
|
1409
|
+
const liveState = () => cleanupLiveStateForRuntime(runtime, protectAllCandidates);
|
|
1410
|
+
const base = await planCleanup(baseStore, scope, liveState, { includeLegacy, previewRootSessionId });
|
|
1411
|
+
if (scope !== "global")
|
|
1412
|
+
return base;
|
|
1413
|
+
const overrides = new Map();
|
|
1414
|
+
for (const [rootSessionId, store] of stores) {
|
|
1415
|
+
if (store.bindingContext?.rootSessionId !== rootSessionId)
|
|
1416
|
+
continue;
|
|
1417
|
+
overrides.set(rootSessionId, await planCleanup(store, "session", liveState, { includeLegacy }));
|
|
1418
|
+
}
|
|
1419
|
+
return mergeCleanupPlans(base, overrides);
|
|
1420
|
+
};
|
|
1421
|
+
let plan = await build();
|
|
1422
|
+
if (runtime.unknownRootActivity) {
|
|
1423
|
+
const roots = new Set(plan.files.map(file => file.rootSessionId).filter(root => root.length > 0));
|
|
1424
|
+
if (roots.size > 0)
|
|
1425
|
+
plan = await build(roots);
|
|
1426
|
+
}
|
|
1427
|
+
return plan;
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Snapshot every live record the preview could select, BEFORE planning or any
|
|
1431
|
+
* UI wait. Plain object identity + the numeric run generation only: a resume
|
|
1432
|
+
* that lands while the preview/confirmation is open must remain a NEW
|
|
1433
|
+
* generation this cleanup never selected.
|
|
1434
|
+
*/
|
|
1435
|
+
function snapshotLiveRecords() {
|
|
1436
|
+
const result = new Map();
|
|
1437
|
+
for (const record of manager.listAgents()) {
|
|
1438
|
+
result.set(record.id, { record, runGeneration: record.runGeneration ?? 0 });
|
|
1439
|
+
}
|
|
1440
|
+
return result;
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* Planned ids that had a live record when the pre-plan snapshot was taken.
|
|
1444
|
+
* A planned id absent from that snapshot is not previewed as live: if a record
|
|
1445
|
+
* exists for it later, it is a NEW live id and its root is conservatively
|
|
1446
|
+
* changed (see the post-confirmation freeze below).
|
|
1447
|
+
*/
|
|
1448
|
+
function selectPreviewRecords(plan, snapshot) {
|
|
1449
|
+
const result = new Map();
|
|
1450
|
+
for (const file of plan.files) {
|
|
1451
|
+
if (file.agentId === undefined || result.has(file.agentId))
|
|
1452
|
+
continue;
|
|
1453
|
+
const captured = snapshot.get(file.agentId);
|
|
1454
|
+
if (captured === undefined)
|
|
1455
|
+
continue;
|
|
1456
|
+
result.set(file.agentId, {
|
|
1457
|
+
record: captured.record,
|
|
1458
|
+
runGeneration: captured.runGeneration,
|
|
1459
|
+
rootSessionId: file.rootSessionId.length > 0 ? file.rootSessionId : captured.record.rootSessionId,
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
return result;
|
|
1463
|
+
}
|
|
1464
|
+
function isSelectedLiveRecord(record, preview) {
|
|
1465
|
+
const snapshot = preview.get(record.id);
|
|
1466
|
+
return snapshot !== undefined
|
|
1467
|
+
&& snapshot.record === record
|
|
1468
|
+
&& snapshot.runGeneration === (record.runGeneration ?? 0)
|
|
1469
|
+
&& record.status !== "running"
|
|
1470
|
+
&& record.status !== "queued";
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* Count the delivery windows confirmation will actually discard — and only
|
|
1474
|
+
* those. Three separate truths are reported separately: unread artifact files
|
|
1475
|
+
* (`counts.unread`), unread LIVE reports (`countSelectedUnreadReports`) and
|
|
1476
|
+
* pending deliveries (here). A workflow's held notice is one window under the
|
|
1477
|
+
* run id, not an agent id; a member whose result was already consumed, or
|
|
1478
|
+
* whose record moved to a newer run, cannot deliver at all and is not counted.
|
|
1479
|
+
*/
|
|
1480
|
+
function countPendingSelectedDeliveries(plan, preview) {
|
|
1481
|
+
const selected = new Set(plan.agentIds);
|
|
1482
|
+
const pending = new Set();
|
|
1483
|
+
const eligible = (id) => {
|
|
1484
|
+
if (!selected.has(id))
|
|
1485
|
+
return false;
|
|
1486
|
+
const snapshot = preview.get(id);
|
|
1487
|
+
if (snapshot === undefined)
|
|
1488
|
+
return false;
|
|
1489
|
+
const record = snapshot.record;
|
|
1490
|
+
// Same record object AND same run generation: a resume makes this a newer
|
|
1491
|
+
// run whose own notification is none of this cleanup's business.
|
|
1492
|
+
if (manager.getRecord(id) !== record)
|
|
1493
|
+
return false;
|
|
1494
|
+
if ((record.runGeneration ?? 0) !== snapshot.runGeneration)
|
|
1495
|
+
return false;
|
|
1496
|
+
if (record.resultConsumed === true)
|
|
1497
|
+
return false;
|
|
1498
|
+
return record.status !== "running" && record.status !== "queued";
|
|
1499
|
+
};
|
|
1500
|
+
const addKeys = (key) => {
|
|
1501
|
+
const ids = key.startsWith("group:") ? key.slice("group:".length).split(",") : [key];
|
|
1502
|
+
for (const id of ids)
|
|
1503
|
+
if (eligible(id))
|
|
1504
|
+
pending.add(id);
|
|
1505
|
+
};
|
|
1506
|
+
for (const key of pendingNudges.keys())
|
|
1507
|
+
addKeys(key);
|
|
1508
|
+
for (const entry of currentBatchAgents)
|
|
1509
|
+
if (eligible(entry.id))
|
|
1510
|
+
pending.add(entry.id);
|
|
1511
|
+
for (const id of selected)
|
|
1512
|
+
if (eligible(id) && groupJoin.isGrouped(id))
|
|
1513
|
+
pending.add(id);
|
|
1514
|
+
for (const file of plan.files) {
|
|
1515
|
+
if (file.workflowId === undefined || !pendingNudges.has(file.workflowId))
|
|
1516
|
+
continue;
|
|
1517
|
+
// Namespaced so a workflow id can never collide with an agent id.
|
|
1518
|
+
pending.add(`workflow:${file.workflowId}`);
|
|
1519
|
+
}
|
|
1520
|
+
return pending.size;
|
|
1521
|
+
}
|
|
1522
|
+
function countSelectedUnreadReports(preview) {
|
|
1523
|
+
let count = 0;
|
|
1524
|
+
for (const snapshot of preview.values()) {
|
|
1525
|
+
if (snapshot.record.resultConsumed !== true)
|
|
1526
|
+
count++;
|
|
1527
|
+
}
|
|
1528
|
+
return count;
|
|
1529
|
+
}
|
|
1530
|
+
function buildCleanupConfirmation(plan, preview) {
|
|
1531
|
+
const unreadReports = countSelectedUnreadReports(preview);
|
|
1532
|
+
const pending = countPendingSelectedDeliveries(plan, preview);
|
|
1533
|
+
const counts = plan.counts;
|
|
1534
|
+
const lines = [
|
|
1535
|
+
`Permanently delete ${counts.files} file(s) (${counts.bytes} bytes) from ${plan.roots.length} root session(s)?`,
|
|
1536
|
+
`${counts.reports} report entries · ${counts.taskOutputs} task outputs · ${counts.workflowFiles} workflow files · ${counts.childSessions} child sessions · ${counts.legacy} legacy outputs · ${counts.diagnostics} diagnostics logs.`,
|
|
1537
|
+
`${counts.unread} unread artifact file(s) are not marked as read; ${unreadReports} live report(s) are not marked as read.`,
|
|
1538
|
+
`${pending} selected completion notification(s) are still pending and will be discarded.`,
|
|
1539
|
+
];
|
|
1540
|
+
if (plan.identityUncertainty !== undefined) {
|
|
1541
|
+
lines.push(`Identity uncertainty: ${plan.identityUncertainty}. Identity-sensitive deletions will be refused.`);
|
|
1542
|
+
}
|
|
1543
|
+
lines.push("This cannot be undone. Your own session history is never a cleanup candidate.");
|
|
1544
|
+
return lines.join("\n");
|
|
1545
|
+
}
|
|
1546
|
+
function beginWorkflowCleanupProof(id, rootSessionId) {
|
|
1547
|
+
workflowCleanupProofs.set(id, {
|
|
1548
|
+
...(rootSessionId === undefined ? {} : { rootSessionId }),
|
|
1549
|
+
generatedPaths: [],
|
|
1550
|
+
externalPaths: [],
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
function updateWorkflowCleanupProof(id, generatedPaths, externalPaths) {
|
|
1554
|
+
const proof = workflowCleanupProofs.get(id);
|
|
1555
|
+
if (proof === undefined)
|
|
1556
|
+
return;
|
|
1557
|
+
proof.generatedPaths = [...generatedPaths];
|
|
1558
|
+
proof.externalPaths = [...externalPaths];
|
|
1559
|
+
}
|
|
1560
|
+
function recordWorkflowPersistenceResult(id, result) {
|
|
1561
|
+
const proof = workflowCleanupProofs.get(id);
|
|
1562
|
+
if (proof === undefined)
|
|
1563
|
+
return;
|
|
1564
|
+
if (result?.saved === false && result.reason !== "persist-disabled") {
|
|
1565
|
+
proof.persistenceUncertainty ??= result.reason;
|
|
1566
|
+
}
|
|
1567
|
+
else if (result?.saved === true) {
|
|
1568
|
+
proof.persistenceUncertainty = undefined;
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
function settleWorkflowCleanupProof(id, result) {
|
|
1572
|
+
const proof = workflowCleanupProofs.get(id);
|
|
1573
|
+
if (proof === undefined)
|
|
1574
|
+
return;
|
|
1575
|
+
if (result === undefined || result.saved === true || result.reason === "persist-disabled") {
|
|
1576
|
+
workflowCleanupProofs.delete(id);
|
|
1577
|
+
return;
|
|
1578
|
+
}
|
|
1579
|
+
proof.persistenceUncertainty ??= result.reason;
|
|
1580
|
+
}
|
|
1581
|
+
function cleanupOperationLiveState(op) {
|
|
1582
|
+
if (!cleanupOperationCurrent(op)) {
|
|
1583
|
+
return { protectedRootSessionIds: [...op.candidateRoots], diagnosticsBusy: true };
|
|
1584
|
+
}
|
|
1585
|
+
const runtime = collectCleanupRuntime();
|
|
1586
|
+
const protectedRoots = new Set([...op.frozenRoots, ...runtime.protectedRoots]);
|
|
1587
|
+
if (runtime.unknownRootActivity) {
|
|
1588
|
+
for (const root of op.candidateRoots)
|
|
1589
|
+
protectedRoots.add(root);
|
|
1590
|
+
}
|
|
1591
|
+
return {
|
|
1592
|
+
activeAgentIds: runtime.activeAgentIds,
|
|
1593
|
+
activeWorkflowIds: runtime.activeWorkflowIds,
|
|
1594
|
+
protectedPaths: runtime.protectedPaths,
|
|
1595
|
+
unreadAgentIds: runtime.unreadAgentIds,
|
|
1596
|
+
diagnosticsBusy: runtime.hasActiveWork,
|
|
1597
|
+
protectedRootSessionIds: protectedRoots,
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
/**
|
|
1601
|
+
* Diagnostics is the one shared global candidate, so it has no per-root
|
|
1602
|
+
* selection to protect it. Its final gate asks each root's OWNING store what
|
|
1603
|
+
* that store really sees: activation/lease/lock liveness and readability,
|
|
1604
|
+
* through the public `rootProtectionReason` view — the same backend policy
|
|
1605
|
+
* that refuses a bind or a cleanup lock. Counting local bindings or comparing
|
|
1606
|
+
* lease counts guesses at ownership: a foreign writer can hold the only active
|
|
1607
|
+
* lease of a root this process merely has a refused context for.
|
|
1608
|
+
*
|
|
1609
|
+
* Own idle roots allow. A live/uncertain lock, an unreadable lease metadata
|
|
1610
|
+
* set, a live foreign lease, or a root that vanished under us all protect.
|
|
1611
|
+
*/
|
|
1612
|
+
async function cleanupForeignDiagnosticsActivity(baseStore) {
|
|
1613
|
+
try {
|
|
1614
|
+
// Strict inventory, never a best-effort list: an unreadable, unsafe or
|
|
1615
|
+
// vanished root is uncertainty, and a partial inventory must protect the
|
|
1616
|
+
// shared aggregate rather than silently shrinking to the readable roots.
|
|
1617
|
+
const scan = await baseStore.scanRootIdentities();
|
|
1618
|
+
const roots = [];
|
|
1619
|
+
let busy = scan.uncertainty !== undefined;
|
|
1620
|
+
for (const state of scan.states) {
|
|
1621
|
+
// The owning store must answer, or its own lease reads as foreign; roots
|
|
1622
|
+
// without one are answered by any store, since all share the same root.
|
|
1623
|
+
const owner = reportStores.get(state.rootSessionId);
|
|
1624
|
+
const store = owner?.bindingContext?.rootSessionId === state.rootSessionId ? owner : baseStore;
|
|
1625
|
+
const reason = await store.rootProtectionReason(state.rootSessionId);
|
|
1626
|
+
if (reason === undefined)
|
|
1627
|
+
continue;
|
|
1628
|
+
busy = true;
|
|
1629
|
+
roots.push(state.rootSessionId);
|
|
1630
|
+
}
|
|
1631
|
+
return { busy, roots };
|
|
1632
|
+
}
|
|
1633
|
+
catch {
|
|
1634
|
+
// Unreadable inventory is itself uncertainty: keep the shared aggregate.
|
|
1635
|
+
return { busy: true, roots: [] };
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
async function diagnosticsCleanupLiveState(op) {
|
|
1639
|
+
const live = cleanupOperationLiveState(op);
|
|
1640
|
+
if (!cleanupOperationCurrent(op))
|
|
1641
|
+
return live;
|
|
1642
|
+
const foreign = await cleanupForeignDiagnosticsActivity(reportStores.get(op.rootSessionId) ?? reportStore);
|
|
1643
|
+
const protectedRoots = new Set(live.protectedRootSessionIds ?? []);
|
|
1644
|
+
for (const root of foreign.roots)
|
|
1645
|
+
protectedRoots.add(root);
|
|
1646
|
+
return {
|
|
1647
|
+
...live,
|
|
1648
|
+
diagnosticsBusy: live.diagnosticsBusy === true || foreign.busy,
|
|
1649
|
+
protectedRootSessionIds: protectedRoots,
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
async function prepareCleanupPartition(op, request) {
|
|
1653
|
+
if (!cleanupOperationCurrent(op))
|
|
1654
|
+
throw new Error("cleanup-session-changed");
|
|
1655
|
+
const runtime = collectCleanupRuntime();
|
|
1656
|
+
const allowed = new Set();
|
|
1657
|
+
if (!runtime.unknownRootActivity) {
|
|
1658
|
+
for (const root of request.rootSessionIds) {
|
|
1659
|
+
if (op.reservedRoots.has(root) && !runtime.protectedRoots.has(root) && !op.frozenRoots.has(root)) {
|
|
1660
|
+
allowed.add(root);
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
const agentIds = request.agentIds.filter(id => {
|
|
1665
|
+
const root = op.planAgentRoots.get(id);
|
|
1666
|
+
return root !== undefined && allowed.has(root);
|
|
1667
|
+
});
|
|
1668
|
+
const sessionFiles = request.sessionFiles.filter(path => {
|
|
1669
|
+
const root = op.planPathRoots.get(cleanupPathKey(path));
|
|
1670
|
+
return root !== undefined && allowed.has(root);
|
|
1671
|
+
});
|
|
1672
|
+
const readyRootSessionIds = request.rootSessionIds.filter(root => allowed.has(root));
|
|
1673
|
+
if (agentIds.length === 0 && sessionFiles.length === 0) {
|
|
1674
|
+
return {
|
|
1675
|
+
readyAgentIds: [],
|
|
1676
|
+
readySessionFiles: [],
|
|
1677
|
+
readyRootSessionIds,
|
|
1678
|
+
...(request.rootSessionIds.some(root => !allowed.has(root))
|
|
1679
|
+
? { blockedRootSessionIds: Object.fromEntries(request.rootSessionIds.filter(root => !allowed.has(root)).map(root => [root, "cleanup-root-not-eligible"])) }
|
|
1680
|
+
: {}),
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
const prepared = await manager.prepareCleanup(agentIds, sessionFiles);
|
|
1684
|
+
return { ...prepared, readyRootSessionIds };
|
|
1685
|
+
}
|
|
1686
|
+
function combineCleanupResults(plan, results) {
|
|
1687
|
+
const deleted = results.flatMap(result => result.deleted);
|
|
1688
|
+
const failed = results.flatMap(result => result.failed);
|
|
1689
|
+
const skipped = [
|
|
1690
|
+
...plan.skipped.map(item => ({ ...item })),
|
|
1691
|
+
...results.flatMap(result => result.skipped),
|
|
1692
|
+
];
|
|
1693
|
+
const deletedAgentIds = new Set();
|
|
1694
|
+
let bytesDeleted = 0;
|
|
1695
|
+
for (const result of results) {
|
|
1696
|
+
for (const id of result.deletedAgentIds)
|
|
1697
|
+
deletedAgentIds.add(id);
|
|
1698
|
+
bytesDeleted += result.bytesDeleted;
|
|
1699
|
+
}
|
|
1700
|
+
return {
|
|
1701
|
+
scope: plan.scope,
|
|
1702
|
+
deleted,
|
|
1703
|
+
failed,
|
|
1704
|
+
skipped,
|
|
1705
|
+
deletedAgentIds: [...deletedAgentIds].sort(),
|
|
1706
|
+
bytesDeleted,
|
|
1707
|
+
};
|
|
1708
|
+
}
|
|
1709
|
+
function formatCleanupResult(result) {
|
|
1710
|
+
const lines = [
|
|
1711
|
+
`Cleanup ${result.scope} finished — ${result.deleted.length} deleted (${result.bytesDeleted} bytes), ${result.failed.length} failed, ${result.skipped.length} skipped.`,
|
|
1712
|
+
];
|
|
1713
|
+
if (result.deleted.length > 0) {
|
|
1714
|
+
lines.push("Deleted:");
|
|
1715
|
+
for (const item of result.deleted) {
|
|
1716
|
+
lines.push(`- ${safeCleanupText(item.path)} (${item.kind}, ${item.bytes} bytes, ${cleanupReadStateLabel(item.readState)})`);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
if (result.failed.length > 0) {
|
|
1720
|
+
lines.push("Failed:");
|
|
1721
|
+
for (const item of result.failed) {
|
|
1722
|
+
lines.push(`- ${item.path === undefined ? `(${item.kind ?? "unknown"})` : safeCleanupText(item.path)}: ${safeCleanupText(item.reason)}`);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
if (result.skipped.length > 0) {
|
|
1726
|
+
lines.push("Skipped:");
|
|
1727
|
+
for (const item of result.skipped) {
|
|
1728
|
+
const where = item.path === undefined
|
|
1729
|
+
? `(${item.kind ?? "unknown"}${item.rootSessionId === undefined ? "" : `, root ${item.rootSessionId}`}${item.agentId === undefined ? "" : `, agent ${item.agentId}`})`
|
|
1730
|
+
: `${safeCleanupText(item.path)} (${item.kind ?? "unknown"})`;
|
|
1731
|
+
lines.push(`- ${where}: ${safeCleanupText(item.reason)}`);
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
return lines.join("\n");
|
|
1735
|
+
}
|
|
1736
|
+
function discardSelectedDeliveries(op, plan, preview) {
|
|
1737
|
+
const allowed = new Set(op.reservedRoots);
|
|
1738
|
+
const selected = new Set();
|
|
1739
|
+
for (const file of plan.files) {
|
|
1740
|
+
if (file.agentId === undefined || !allowed.has(file.rootSessionId))
|
|
1741
|
+
continue;
|
|
1742
|
+
const snapshot = preview.get(file.agentId);
|
|
1743
|
+
if (snapshot === undefined || !isSelectedLiveRecord(snapshot.record, preview))
|
|
1744
|
+
continue;
|
|
1745
|
+
selected.add(file.agentId);
|
|
1746
|
+
}
|
|
1747
|
+
for (const id of selected) {
|
|
1748
|
+
const record = manager.getRecord(id);
|
|
1749
|
+
if (record === undefined)
|
|
1750
|
+
continue;
|
|
1751
|
+
record.resultConsumed = true;
|
|
1752
|
+
cancelNudge(id);
|
|
1753
|
+
deferredResultInterest.delete(id);
|
|
1754
|
+
}
|
|
1755
|
+
const remainingBatch = currentBatchAgents.filter(entry => !selected.has(entry.id));
|
|
1756
|
+
if (remainingBatch.length !== currentBatchAgents.length) {
|
|
1757
|
+
currentBatchAgents = remainingBatch;
|
|
1758
|
+
if (currentBatchAgents.length === 0 && batchFinalizeTimer !== undefined) {
|
|
1759
|
+
clearTimeout(batchFinalizeTimer);
|
|
1760
|
+
batchFinalizeTimer = undefined;
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
for (const workflowId of plan.files
|
|
1764
|
+
.filter(file => workflowIdOf(file) !== undefined && allowed.has(file.rootSessionId))
|
|
1765
|
+
.map(file => workflowIdOf(file))
|
|
1766
|
+
.filter((id) => id !== undefined)) {
|
|
1767
|
+
op.selectedWorkflowIds.add(workflowId);
|
|
1768
|
+
discardedWorkflowNotifications.add(workflowId);
|
|
1769
|
+
cancelNudge(workflowId);
|
|
1770
|
+
}
|
|
1771
|
+
groupJoin.discard(selected);
|
|
1772
|
+
}
|
|
1773
|
+
function workflowIdOf(file) {
|
|
1774
|
+
return file.workflowId;
|
|
1775
|
+
}
|
|
1776
|
+
function forgetDeletedWorkflowPointers(result) {
|
|
1777
|
+
for (const file of result.deleted) {
|
|
1778
|
+
if (file.kind !== "workflow-registration" || file.workflowId === undefined)
|
|
1779
|
+
continue;
|
|
1780
|
+
const ownedRoot = workflowArtifactRoots.get(file.workflowId);
|
|
1781
|
+
if (ownedRoot !== undefined && ownedRoot !== file.rootSessionId)
|
|
1782
|
+
continue;
|
|
1783
|
+
workflowTasks.delete(file.workflowId);
|
|
1784
|
+
workflowArtifactPaths.delete(file.workflowId);
|
|
1785
|
+
workflowArtifactRoots.delete(file.workflowId);
|
|
1786
|
+
workflowArtifactStores.delete(file.workflowId);
|
|
1787
|
+
workflowCleanupProofs.delete(file.workflowId);
|
|
1788
|
+
// The run promise and its journal drain are deliberately NOT dropped
|
|
1789
|
+
// here: a deleted registration is not proof that the run stopped writing,
|
|
1790
|
+
// and shutdown must still await whatever it accepted. Those handles are
|
|
1791
|
+
// removed by the run settling, never by pointer forgetting.
|
|
1792
|
+
// The send-time invalidation deliberately OUTLIVES pointer forgetting. A
|
|
1793
|
+
// hold callback can already be sitting in the timer queue when cleanup
|
|
1794
|
+
// finishes, and it rechecks this set on entry: dropping the flag together
|
|
1795
|
+
// with the pointers would let that queued callback announce a run whose
|
|
1796
|
+
// registration this cleanup just deleted.
|
|
1797
|
+
}
|
|
1798
|
+
for (const file of result.deleted) {
|
|
1799
|
+
if (file.kind === "workflow-generated")
|
|
1800
|
+
knownGeneratedWorkflowPaths.delete(resolve(file.path));
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
async function handleCleanupCommand(tokens, ctx) {
|
|
1804
|
+
const parsed = parseCleanupArgs(tokens);
|
|
1805
|
+
if (parsed === undefined) {
|
|
1806
|
+
ctx.ui.notify(cleanupUsage(), "warning");
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
const rootSessionId = ctx.sessionManager?.getSessionId?.();
|
|
1810
|
+
if (rootSessionId === undefined) {
|
|
1811
|
+
ctx.ui.notify("Cleanup is unavailable without a bound session.", "warning");
|
|
1812
|
+
return;
|
|
1813
|
+
}
|
|
1814
|
+
const epoch = sessionEpoch;
|
|
1815
|
+
const readRoot = () => ctx.sessionManager?.getSessionId?.();
|
|
1816
|
+
// Dry-run is strictly read-only: never rebind a root, retire another
|
|
1817
|
+
// store's lease, or drain deferred archive writes just to render a preview.
|
|
1818
|
+
if (!parsed.dryRun)
|
|
1819
|
+
await ensureReportBinding(ctx);
|
|
1820
|
+
if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
|
|
1821
|
+
ctx.ui.notify("Cleanup cancelled — the session changed before preview.", "warning");
|
|
1822
|
+
return;
|
|
1823
|
+
}
|
|
1824
|
+
const baseStore = reportStores.get(rootSessionId) ?? reportStore;
|
|
1825
|
+
if (!parsed.dryRun && baseStore.bindingContext?.rootSessionId !== rootSessionId) {
|
|
1826
|
+
ctx.ui.notify("Cleanup refused — the bound report store does not belong to this session.", "warning");
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
const stores = new Map(reportStores);
|
|
1830
|
+
if (!parsed.dryRun && !stores.has(rootSessionId))
|
|
1831
|
+
stores.set(rootSessionId, baseStore);
|
|
1832
|
+
// Taken BEFORE every planning/UI await: the preview must describe the
|
|
1833
|
+
// generations that existed when it opened, not whatever a resume leaves
|
|
1834
|
+
// behind by the time confirmation arrives.
|
|
1835
|
+
const initialPreviewRecords = snapshotLiveRecords();
|
|
1836
|
+
if (!parsed.dryRun)
|
|
1837
|
+
drainPendingArchivedRecords();
|
|
1838
|
+
try {
|
|
1839
|
+
const drained = await Promise.all([...new Set([...stores.values(), baseStore])].map(store => store.flush()));
|
|
1840
|
+
if (drained.some(result => result.status !== "flushed"))
|
|
1841
|
+
throw new Error("incomplete report flush");
|
|
1842
|
+
}
|
|
1843
|
+
catch {
|
|
1844
|
+
ctx.ui.notify("Cleanup refused — pending report writes could not be flushed.", "warning");
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
const runtime = collectCleanupRuntime();
|
|
1848
|
+
let plan;
|
|
1849
|
+
try {
|
|
1850
|
+
plan = await buildCleanupPreviewPlan(baseStore, parsed.scope, parsed.includeLegacy, runtime, stores, parsed.dryRun && parsed.scope === "session" ? rootSessionId : undefined);
|
|
1851
|
+
}
|
|
1852
|
+
catch (error) {
|
|
1853
|
+
ctx.ui.notify(`Cleanup preview failed: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
|
|
1857
|
+
ctx.ui.notify("Cleanup cancelled — the session changed before preview.", "warning");
|
|
1858
|
+
return;
|
|
1859
|
+
}
|
|
1860
|
+
const previewText = formatCleanupPreview(plan);
|
|
1861
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) {
|
|
1862
|
+
ctx.ui.notify(`${previewText}\n\nCleanup needs the native terminal UI for its review and confirmation; nothing was deleted. Run it interactively, or use --dry-run here to inspect this inventory.`, parsed.dryRun ? "info" : "warning");
|
|
1863
|
+
return;
|
|
1864
|
+
}
|
|
1865
|
+
let reviewed = false;
|
|
1866
|
+
try {
|
|
1867
|
+
reviewed = await showCleanupPreview(ctx, plan, parsed.dryRun);
|
|
1868
|
+
}
|
|
1869
|
+
catch {
|
|
1870
|
+
reviewed = false;
|
|
1871
|
+
}
|
|
1872
|
+
if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
|
|
1873
|
+
ctx.ui.notify("Cleanup cancelled — the session changed during preview.", "warning");
|
|
1874
|
+
return;
|
|
1875
|
+
}
|
|
1876
|
+
if (!reviewed) {
|
|
1877
|
+
ctx.ui.notify(parsed.dryRun ? "Dry run closed — nothing was deleted." : "Cleanup cancelled — nothing was deleted.", "info");
|
|
1878
|
+
return;
|
|
1879
|
+
}
|
|
1880
|
+
if (parsed.dryRun) {
|
|
1881
|
+
ctx.ui.notify("Dry run complete — nothing was deleted.", "info");
|
|
1882
|
+
return;
|
|
1883
|
+
}
|
|
1884
|
+
if (plan.files.length === 0) {
|
|
1885
|
+
ctx.ui.notify("Nothing is eligible for cleanup.", "info");
|
|
1886
|
+
return;
|
|
1887
|
+
}
|
|
1888
|
+
const previewRecords = selectPreviewRecords(plan, initialPreviewRecords);
|
|
1889
|
+
const confirmed = await ctx.ui.confirm("Confirm cleanup", buildCleanupConfirmation(plan, previewRecords));
|
|
1890
|
+
if (!confirmed) {
|
|
1891
|
+
ctx.ui.notify("Cleanup cancelled — nothing was deleted.", "info");
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
|
|
1895
|
+
ctx.ui.notify("Cleanup cancelled — the session changed before deletion.", "warning");
|
|
1896
|
+
return;
|
|
1897
|
+
}
|
|
1898
|
+
let legacyConfirmed = false;
|
|
1899
|
+
if (plan.files.some(file => file.kind === "legacy-output")) {
|
|
1900
|
+
const legacyCount = plan.files.filter(file => file.kind === "legacy-output").length;
|
|
1901
|
+
legacyConfirmed = await ctx.ui.confirm("Confirm legacy cleanup", `Delete ${legacyCount} legacy .output file(s)? Older pi instances must be closed first; a live instance may still hold these files.`);
|
|
1902
|
+
if (!legacyConfirmed) {
|
|
1903
|
+
ctx.ui.notify("Cleanup cancelled — nothing was deleted.", "info");
|
|
1904
|
+
return;
|
|
1905
|
+
}
|
|
1906
|
+
if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
|
|
1907
|
+
ctx.ui.notify("Cleanup cancelled — the session changed before deletion.", "warning");
|
|
1908
|
+
return;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
const after = collectCleanupRuntime();
|
|
1912
|
+
const candidateRoots = new Set(plan.files.map(file => file.rootSessionId).filter(root => root.length > 0));
|
|
1913
|
+
const frozenRoots = new Set(after.protectedRoots);
|
|
1914
|
+
if (after.unknownRootActivity) {
|
|
1915
|
+
for (const root of candidateRoots)
|
|
1916
|
+
frozenRoots.add(root);
|
|
1917
|
+
}
|
|
1918
|
+
const plannedAgentRoots = new Map();
|
|
1919
|
+
for (const file of plan.files) {
|
|
1920
|
+
if (file.agentId !== undefined && !plannedAgentRoots.has(file.agentId)) {
|
|
1921
|
+
plannedAgentRoots.set(file.agentId, file.rootSessionId);
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
const freezeChangedRoot = (root) => {
|
|
1925
|
+
if (root !== undefined && root.length > 0)
|
|
1926
|
+
frozenRoots.add(root);
|
|
1927
|
+
else
|
|
1928
|
+
for (const candidate of candidateRoots)
|
|
1929
|
+
frozenRoots.add(candidate);
|
|
1930
|
+
};
|
|
1931
|
+
// Every planned agent id, not only the ones the snapshot happened to hold:
|
|
1932
|
+
// an id with no record at preview time that has one now is a live id this
|
|
1933
|
+
// preview never selected, so its root is conservatively changed. A record
|
|
1934
|
+
// that vanished with no new run leaves no writer and no notice to protect.
|
|
1935
|
+
for (const [id, plannedRoot] of plannedAgentRoots) {
|
|
1936
|
+
const snapshot = initialPreviewRecords.get(id);
|
|
1937
|
+
const current = manager.getRecord(id);
|
|
1938
|
+
if (snapshot === undefined) {
|
|
1939
|
+
if (current !== undefined)
|
|
1940
|
+
freezeChangedRoot(current.rootSessionId ?? plannedRoot);
|
|
1941
|
+
continue;
|
|
1942
|
+
}
|
|
1943
|
+
if (current === undefined)
|
|
1944
|
+
continue;
|
|
1945
|
+
if (current === snapshot.record && (current.runGeneration ?? 0) === snapshot.runGeneration)
|
|
1946
|
+
continue;
|
|
1947
|
+
freezeChangedRoot(snapshot.record.rootSessionId ?? plannedRoot);
|
|
1948
|
+
}
|
|
1949
|
+
const reservedRoots = new Set([...candidateRoots].filter(root => !frozenRoots.has(root)));
|
|
1950
|
+
const op = {
|
|
1951
|
+
epoch,
|
|
1952
|
+
rootSessionId,
|
|
1953
|
+
readRoot,
|
|
1954
|
+
candidateRoots,
|
|
1955
|
+
frozenRoots,
|
|
1956
|
+
reservedRoots,
|
|
1957
|
+
selectedAgentIds: new Set(plan.agentIds),
|
|
1958
|
+
selectedSessionFiles: new Set(plan.sessionFiles.map(cleanupPathKey)),
|
|
1959
|
+
selectedPaths: new Set(plan.files.map(file => cleanupPathKey(file.path))),
|
|
1960
|
+
selectedWorkflowIds: new Set(),
|
|
1961
|
+
planAgentRoots: new Map(plannedAgentRoots),
|
|
1962
|
+
planPathRoots: new Map(),
|
|
1963
|
+
};
|
|
1964
|
+
for (const file of plan.files) {
|
|
1965
|
+
op.planPathRoots.set(cleanupPathKey(file.path), file.rootSessionId);
|
|
1966
|
+
if (file.kind === "child-session" && file.sessionFile !== undefined) {
|
|
1967
|
+
op.planPathRoots.set(cleanupPathKey(file.sessionFile), file.rootSessionId);
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
// Exactly one operation owns the reservations: a second confirmed cleanup
|
|
1971
|
+
// must not overwrite this owner, or its release would clear barriers the
|
|
1972
|
+
// first pass is still relying on.
|
|
1973
|
+
if (cleanupOperation !== undefined && cleanupOperationCurrent(cleanupOperation)) {
|
|
1974
|
+
ctx.ui.notify("Another cleanup is already applying in this session; nothing was deleted.", "warning");
|
|
585
1975
|
return;
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
1976
|
+
}
|
|
1977
|
+
cleanupOperation = op;
|
|
1978
|
+
// From here every archived read of a candidate root is suspect, including
|
|
1979
|
+
// one that resumes after this operation has already released.
|
|
1980
|
+
invalidateCleanupReads(op.candidateRoots);
|
|
1981
|
+
const results = [];
|
|
1982
|
+
let interrupted = false;
|
|
1983
|
+
try {
|
|
1984
|
+
// Consume the eligible selected deliveries SYNCHRONOUSLY, before this
|
|
1985
|
+
// operation's first await. A held individual/group/workflow notice can
|
|
1986
|
+
// reach its deadline during the root-generation reads below, and cleanup
|
|
1987
|
+
// cannot withdraw a message that was already sent. A later generation or
|
|
1988
|
+
// deletion failure does not roll this back: the discard is deliberate.
|
|
1989
|
+
discardSelectedDeliveries(op, plan, previewRecords);
|
|
1990
|
+
if (!cleanupOperationCurrent(op))
|
|
1991
|
+
interrupted = true;
|
|
1992
|
+
// Recheck the confirmed root generations ONLY after every idle candidate
|
|
1993
|
+
// root is reserved, so no producer can slip into the gap. This still
|
|
1994
|
+
// precedes every deletion.
|
|
1995
|
+
const changedRoots = new Set();
|
|
1996
|
+
await Promise.all([...reservedRoots].map(async (root) => {
|
|
1997
|
+
const planned = plan.roots.find(item => item.rootSessionId === root);
|
|
1998
|
+
if (planned === undefined)
|
|
1999
|
+
return;
|
|
2000
|
+
const store = stores.get(root) ?? baseStore;
|
|
2001
|
+
const current = await store.getRootGeneration(root);
|
|
2002
|
+
if ((current ?? 0) !== planned.generation)
|
|
2003
|
+
changedRoots.add(root);
|
|
2004
|
+
}));
|
|
2005
|
+
for (const root of changedRoots) {
|
|
2006
|
+
op.reservedRoots.delete(root);
|
|
2007
|
+
op.frozenRoots.add(root);
|
|
2008
|
+
}
|
|
2009
|
+
if (!cleanupOperationCurrent(op))
|
|
2010
|
+
interrupted = true;
|
|
2011
|
+
const parts = partitionCleanupPlan(plan);
|
|
2012
|
+
for (const part of parts) {
|
|
2013
|
+
const root = part.files[0]?.rootSessionId ?? "";
|
|
2014
|
+
const store = root === "" || !stores.has(root) ? baseStore : stores.get(root);
|
|
2015
|
+
const result = await applyCleanup(store, part, {
|
|
2016
|
+
confirmed: true,
|
|
2017
|
+
confirmedLegacy: legacyConfirmed,
|
|
2018
|
+
liveStateGetter: () => root === "" ? diagnosticsCleanupLiveState(op) : Promise.resolve(cleanupOperationLiveState(op)),
|
|
2019
|
+
prepare: request => prepareCleanupPartition(op, request),
|
|
2020
|
+
});
|
|
2021
|
+
results.push(result);
|
|
2022
|
+
if (!cleanupOperationCurrent(op))
|
|
2023
|
+
interrupted = true;
|
|
2024
|
+
}
|
|
2025
|
+
const combined = combineCleanupResults(plan, results);
|
|
2026
|
+
markUnprovenCleanupReports(combined);
|
|
2027
|
+
const deletedSessionFiles = combined.deleted
|
|
2028
|
+
.filter(item => item.kind === "child-session")
|
|
2029
|
+
.map(item => item.path);
|
|
2030
|
+
manager.forgetCleanup(combined.deletedAgentIds, deletedSessionFiles);
|
|
2031
|
+
forgetDeletedWorkflowPointers(combined);
|
|
2032
|
+
const text = formatCleanupResult(combined)
|
|
2033
|
+
+ (interrupted ? "\nCleanup interrupted — the session changed; any remaining candidates were not deleted." : "");
|
|
2034
|
+
ctx.ui.notify(text, combined.failed.length > 0 || interrupted ? "warning" : "info");
|
|
2035
|
+
}
|
|
2036
|
+
catch (error) {
|
|
2037
|
+
// A thrown store/diagnostic error can follow a partially applied plan, and
|
|
2038
|
+
// the partition that rejected has usually committed work of its own. Its
|
|
2039
|
+
// handoff carries that exact progress, so the deletions are reported and
|
|
2040
|
+
// forgotten instead of leaving live reports readable whose durable entries
|
|
2041
|
+
// are already deletion receipts. Never retry or freshen the confirmed plan
|
|
2042
|
+
// here.
|
|
2043
|
+
if (error instanceof CleanupApplyError)
|
|
2044
|
+
results.push(error.result);
|
|
2045
|
+
const partial = combineCleanupResults(plan, results);
|
|
2046
|
+
// A rejected receipt write may already have committed: report it as a
|
|
2047
|
+
// failure AND refuse the cached live body, never as a deletion.
|
|
2048
|
+
markUnprovenCleanupReports(partial);
|
|
2049
|
+
const deletedSessionFiles = partial.deleted
|
|
2050
|
+
.filter(item => item.kind === "child-session")
|
|
2051
|
+
.map(item => item.path);
|
|
2052
|
+
manager.forgetCleanup(partial.deletedAgentIds, deletedSessionFiles);
|
|
2053
|
+
forgetDeletedWorkflowPointers(partial);
|
|
2054
|
+
ctx.ui.notify(`${formatCleanupResult(partial)}\nCleanup failed: ${safeCleanupText(error instanceof Error ? error.message : String(error))}`, "warning");
|
|
2055
|
+
}
|
|
2056
|
+
finally {
|
|
2057
|
+
// Only the owner releases the operation; a second command's reservations
|
|
2058
|
+
// are never cleared by this one's exit.
|
|
2059
|
+
if (cleanupOperation === op)
|
|
2060
|
+
cleanupOperation = undefined;
|
|
2061
|
+
// Closing edge of the read-invalidation interval: a read still holding a
|
|
2062
|
+
// body from before this operation must re-resolve even now that the
|
|
2063
|
+
// barriers are gone.
|
|
2064
|
+
invalidateCleanupReads(op.candidateRoots);
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
603
2067
|
// Expose manager via Symbol.for() global registry for cross-package access.
|
|
604
2068
|
// Standard Node.js pattern for cross-package singletons (used by OpenTelemetry, etc.).
|
|
605
2069
|
// Documented for callers in docs/rpc.md ("The manager registry").
|
|
@@ -617,22 +2081,49 @@ export default function (pi) {
|
|
|
617
2081
|
* Resolve the agent type and spawn. Trusts its options — every caller must
|
|
618
2082
|
* either be in-process or have gone through `spawnTopLevel` first.
|
|
619
2083
|
*/
|
|
620
|
-
const spawnResolved = (piRef, ctxRef, type, prompt, options) => {
|
|
621
|
-
//
|
|
622
|
-
//
|
|
623
|
-
//
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
2084
|
+
const spawnResolved = (piRef, ctxRef, type, prompt, options, cleanupPrepared = false) => {
|
|
2085
|
+
// Only private callers that awaited the store barrier skip synchronous I/O.
|
|
2086
|
+
// Recheck local reservations in this same tick; the manager still guards
|
|
2087
|
+
// the actual start. The public synchronous registry keeps its fresh guard.
|
|
2088
|
+
const rootSessionId = ctxRef?.sessionManager?.getSessionId?.();
|
|
2089
|
+
const paths = [options?.resumeSessionFile];
|
|
2090
|
+
if (cleanupPrepared)
|
|
2091
|
+
assertCleanupLocalAccess(rootSessionId, paths);
|
|
2092
|
+
else
|
|
2093
|
+
assertCleanupRootAccess(rootSessionId, paths);
|
|
2094
|
+
// A prepared caller (the RPC `prepare` registry) already resolved its type
|
|
2095
|
+
// and froze its definition before this synchronous hand-off. Re-resolving
|
|
2096
|
+
// against this process's global registry would discard that snapshot and
|
|
2097
|
+
// could admit a different same-name definition. Unprepared callers keep the
|
|
2098
|
+
// deliberate fresh synchronous reload/resolution below.
|
|
2099
|
+
const admittedDefinition = options?.agentDefinition === undefined
|
|
2100
|
+
? undefined
|
|
2101
|
+
: cloneAgentDefinition(options.agentDefinition);
|
|
2102
|
+
let spawnType = type;
|
|
2103
|
+
if (admittedDefinition === undefined) {
|
|
2104
|
+
// Cross-extension callers get the same dispatch contract as the LLM (#183).
|
|
2105
|
+
// The RPC layer already throws for an unresolvable model rather than falling
|
|
2106
|
+
// back silently; a bad agent type should not be quieter. Throws become error
|
|
2107
|
+
// envelopes at the RPC boundary. Reload first so an agent file added mid
|
|
2108
|
+
// session is spawnable here too, not only through the Agent tool.
|
|
2109
|
+
reloadCustomAgents();
|
|
2110
|
+
const dispatch = resolveSpawnType(type);
|
|
2111
|
+
if (!dispatch.ok) {
|
|
2112
|
+
logSubagentIssue({ kind: "spawn_rejected", requestedType: String(type), reason: dispatch.message });
|
|
2113
|
+
throw new Error(dispatch.message);
|
|
2114
|
+
}
|
|
2115
|
+
spawnType = dispatch.type;
|
|
631
2116
|
}
|
|
2117
|
+
// Bus RPC and the cross-package registry land here synchronously, without
|
|
2118
|
+
// the Agent tool's awaited admission. A persistent root with no proven-active
|
|
2119
|
+
// store must not open a new id or SDK history: the cleanup root guard above
|
|
2120
|
+
// cannot see an absent store, and a foreign lock's selection names OLDER ids,
|
|
2121
|
+
// never the id about to be created. Ephemeral contexts keep their behavior.
|
|
2122
|
+
assertReportBindingAdmission(ctxRef);
|
|
632
2123
|
// Every programmatic spawn lands here — cross-extension RPC, both `@handle`
|
|
633
2124
|
// mention paths, and the `Symbol.for("pi-subagents:manager")` registry — and
|
|
634
2125
|
// none came through the Agent tool, which is where the UI activity tracker is
|
|
635
|
-
// otherwise created. Without one the widget
|
|
2126
|
+
// otherwise created. Without one the widget has no tool name
|
|
636
2127
|
// and no turn count, so the row reads `thinking…` for the agent's whole life
|
|
637
2128
|
// while the header's tool-use count climbs beside it (#181). Double-tracking
|
|
638
2129
|
// is not possible: the Agent tool calls `manager.spawn` directly. The tracker
|
|
@@ -644,14 +2135,23 @@ export default function (pi) {
|
|
|
644
2135
|
// built with `undefined` renders `↻3` where the Agent tool renders `↻3≤20`.
|
|
645
2136
|
// Like the tool's own, it is a prediction — editing the agent file mid-run
|
|
646
2137
|
// leaves the displayed ceiling stale.
|
|
647
|
-
const { state, callbacks } = createActivityTracker(resolveEffectiveMaxTurns(
|
|
2138
|
+
const { state, callbacks } = createActivityTracker(resolveEffectiveMaxTurns(spawnType, options?.maxTurns));
|
|
648
2139
|
// Repaints are left to the manager's `onStart` callback, which already starts
|
|
649
|
-
// the widget
|
|
650
|
-
const id = manager.spawn(piRef, ctxRef,
|
|
2140
|
+
// the widget timer for agents that enter this way.
|
|
2141
|
+
const id = manager.spawn(piRef, ctxRef, spawnType, prompt, {
|
|
2142
|
+
...options,
|
|
2143
|
+
...(admittedDefinition === undefined ? {} : { agentDefinition: admittedDefinition }),
|
|
2144
|
+
...callbacks,
|
|
2145
|
+
});
|
|
651
2146
|
agentActivity.set(id, state);
|
|
652
2147
|
return id;
|
|
653
2148
|
};
|
|
654
|
-
|
|
2149
|
+
/**
|
|
2150
|
+
* Strip internals a process-external caller must never supply. A trusted
|
|
2151
|
+
* prepared definition is kept only for the RPC boundary below, which attaches
|
|
2152
|
+
* it AFTER deleting any caller-supplied value.
|
|
2153
|
+
*/
|
|
2154
|
+
const sanitizeTopLevelOptions = (options, keepAgentDefinition = false) => {
|
|
655
2155
|
const safeOptions = { ...(options ?? {}) };
|
|
656
2156
|
delete safeOptions.parentAgentId;
|
|
657
2157
|
// Internal too: a forged value would hide an RPC-spawned agent inside
|
|
@@ -663,6 +2163,11 @@ export default function (pi) {
|
|
|
663
2163
|
// Also internal: it names a transcript directory, so a forged value would
|
|
664
2164
|
// be a path-traversal primitive.
|
|
665
2165
|
delete safeOptions.rootSessionId;
|
|
2166
|
+
// Root provenance and owner lineage are pinned by the manager from the
|
|
2167
|
+
// live parent chain/context; a caller must not forge either.
|
|
2168
|
+
delete safeOptions.rootCwd;
|
|
2169
|
+
delete safeOptions.rootSessionFile;
|
|
2170
|
+
delete safeOptions.ownerIds;
|
|
666
2171
|
// Worse than rootSessionId: this one names a file to OPEN and replay as a
|
|
667
2172
|
// conversation. Only the mention dispatcher may set it, and only from a
|
|
668
2173
|
// path this extension itself recorded — never from anything a caller sent.
|
|
@@ -674,8 +2179,20 @@ export default function (pi) {
|
|
|
674
2179
|
// awaits nothing. A forged `blocking` would charge it to the foreground
|
|
675
2180
|
// pool and could defer it behind a queue whose gate nobody is holding.
|
|
676
2181
|
delete safeOptions.blocking;
|
|
677
|
-
|
|
2182
|
+
// A definition snapshot is an admission capability: it decides prompt, tool
|
|
2183
|
+
// permissions, model and nesting policy. Only the RPC handler may forward
|
|
2184
|
+
// the one it resolved from its own scoped `prepare` registry.
|
|
2185
|
+
if (!keepAgentDefinition)
|
|
2186
|
+
delete safeOptions.agentDefinition;
|
|
2187
|
+
return safeOptions;
|
|
678
2188
|
};
|
|
2189
|
+
const spawnTopLevel = (piRef, ctxRef, type, prompt, options) => spawnResolved(piRef, ctxRef, type, prompt, sanitizeTopLevelOptions(options));
|
|
2190
|
+
/**
|
|
2191
|
+
* RPC spawns arrive through `registerRpcHandlers`, which deletes any
|
|
2192
|
+
* caller-supplied definition and attaches the one resolved from the scoped
|
|
2193
|
+
* `prepare` registry. Preserve exactly that snapshot across sanitization.
|
|
2194
|
+
*/
|
|
2195
|
+
const spawnRpcPrepared = (piRef, ctxRef, type, prompt, options) => spawnResolved(piRef, ctxRef, type, prompt, sanitizeTopLevelOptions(options, true), true);
|
|
679
2196
|
/**
|
|
680
2197
|
* Resolve a tool's `agent_id` as an id OR a handle, so the model addresses
|
|
681
2198
|
* agents by the same names the user types. Ids are tried first, keeping the
|
|
@@ -699,10 +2216,23 @@ export default function (pi) {
|
|
|
699
2216
|
return record !== undefined && isTopLevelAgent(record) ? record : undefined;
|
|
700
2217
|
},
|
|
701
2218
|
};
|
|
702
|
-
const
|
|
2219
|
+
const managerRegistryHost = globalThis;
|
|
2220
|
+
const ownsManagerRegistry = managerRegistryHost[MANAGER_KEY] === undefined;
|
|
703
2221
|
if (ownsManagerRegistry) {
|
|
704
|
-
|
|
2222
|
+
managerRegistryHost[MANAGER_KEY] = registryEntry;
|
|
705
2223
|
}
|
|
2224
|
+
// --- Goal-orchestration bridge (optional, additive) ---
|
|
2225
|
+
// Constructed at the factory but bound only in session_start; it reads the
|
|
2226
|
+
// manager this activation owns, never the process-global registry, and adds
|
|
2227
|
+
// no lifecycle broadcast of its own beyond the session-scoped ready hint.
|
|
2228
|
+
const goalBridge = new SubagentsGoalBridge({
|
|
2229
|
+
events: pi.events,
|
|
2230
|
+
source: {
|
|
2231
|
+
listAgents: () => manager.listAgents(),
|
|
2232
|
+
getRecord: (id) => manager.getRecord(id),
|
|
2233
|
+
steerAcknowledged: (id, message) => manager.steerAcknowledged(id, message),
|
|
2234
|
+
},
|
|
2235
|
+
});
|
|
706
2236
|
// --- Cross-extension RPC via pi.events ---
|
|
707
2237
|
let currentCtx;
|
|
708
2238
|
// RPC handlers + the `subagents:ready` broadcast are wired on `session_start`
|
|
@@ -740,6 +2270,8 @@ export default function (pi) {
|
|
|
740
2270
|
// This also wires the RPC handlers and broadcasts readiness — on the first
|
|
741
2271
|
// bound session_start, so a filtered-out activation never advertises (#142).
|
|
742
2272
|
pi.on("session_start", async (_event, ctx) => {
|
|
2273
|
+
sessionEpoch++;
|
|
2274
|
+
shuttingDown = false;
|
|
743
2275
|
currentCtx = ctx;
|
|
744
2276
|
// pi's own spinner gate: we mirror terminal.showTerminalProgress so a
|
|
745
2277
|
// user who opted out of terminal progress doesn't get a subagent-driven
|
|
@@ -749,9 +2281,30 @@ export default function (pi) {
|
|
|
749
2281
|
terminalProgress.refresh();
|
|
750
2282
|
if (ctx.hasUI) {
|
|
751
2283
|
widget.setUICtx(ctx.ui);
|
|
752
|
-
fleet.setUICtx(ctx.ui);
|
|
753
2284
|
}
|
|
2285
|
+
// Awaitable refresh for this session's start. The factory load above stays
|
|
2286
|
+
// authoritative for the initial registration; this only picks up files that
|
|
2287
|
+
// changed since. It is NOT fire-and-forget: RPC/mention consumers wired
|
|
2288
|
+
// below must see the fresh global registry until their own scoped reload.
|
|
2289
|
+
await reloadCustomAgentsAsync();
|
|
2290
|
+
// Bind the durable report root before the session yields to any tool.
|
|
2291
|
+
// Deliberately after the synchronous UI capture above: a session_start
|
|
2292
|
+
// caller that does not await must still see the widget bound in the same
|
|
2293
|
+
// tick. Plain metadata is pinned here; no async continuation closes over
|
|
2294
|
+
// the ExtensionContext.
|
|
2295
|
+
// Evict first: roots whose records are all gone can then be drained,
|
|
2296
|
+
// closed and removed instead of accumulating for the process lifetime.
|
|
754
2297
|
manager.clearCompleted(true);
|
|
2298
|
+
await ensureReportBinding(ctx);
|
|
2299
|
+
// Bind the goal bridge only now: manager and session id are live. A repeat
|
|
2300
|
+
// session_start for the same id keeps the existing listener/ledger; a new
|
|
2301
|
+
// id rebinds (releasing the previous listeners first).
|
|
2302
|
+
const goalSessionId = ctx.sessionManager?.getSessionId?.();
|
|
2303
|
+
if (goalSessionId && goalBridge.sessionId !== goalSessionId)
|
|
2304
|
+
goalBridge.bind(goalSessionId);
|
|
2305
|
+
// A new session inherits no deferred wait: its owner was a turn in the last
|
|
2306
|
+
// one, and its wakeup channel died with it.
|
|
2307
|
+
deferredResultInterest.clear();
|
|
755
2308
|
// Guard mirrors the `!scheduler.isActive()` pattern below: session_start
|
|
756
2309
|
// fires once per activation, but a double-bind must not leak listeners.
|
|
757
2310
|
if (!rpcHandle) {
|
|
@@ -759,8 +2312,24 @@ export default function (pi) {
|
|
|
759
2312
|
events: pi.events,
|
|
760
2313
|
pi,
|
|
761
2314
|
getCtx: () => currentCtx,
|
|
2315
|
+
/** Resolve definitions and await root admission before a new id exists. */
|
|
2316
|
+
prepare: async () => {
|
|
2317
|
+
const admissionCtx = currentCtx;
|
|
2318
|
+
const admissionEpoch = sessionEpoch;
|
|
2319
|
+
const rootSessionId = admissionCtx?.sessionManager?.getSessionId?.();
|
|
2320
|
+
const registry = await reloadCustomAgentsAsync();
|
|
2321
|
+
await assertCleanupRootAccessAsync(rootSessionId);
|
|
2322
|
+
if (currentCtx === undefined || sessionEpoch !== admissionEpoch
|
|
2323
|
+
|| admissionCtx?.sessionManager?.getSessionId?.() !== rootSessionId
|
|
2324
|
+
|| currentCtx.sessionManager?.getSessionId?.() !== rootSessionId) {
|
|
2325
|
+
throw new ReportUnavailableError("inactive-activation");
|
|
2326
|
+
}
|
|
2327
|
+
return registry;
|
|
2328
|
+
},
|
|
762
2329
|
manager: {
|
|
763
|
-
|
|
2330
|
+
// The handler has already stripped a caller-supplied definition and
|
|
2331
|
+
// attached the one resolved from `prepare`; preserve that snapshot.
|
|
2332
|
+
spawn: spawnRpcPrepared,
|
|
764
2333
|
awaitStartup: (id) => manager.awaitStartup(id),
|
|
765
2334
|
getRecord: (id) => manager.getRecord(id),
|
|
766
2335
|
// Unguarded on purpose: the stop handler now runs the top-level check
|
|
@@ -778,6 +2347,9 @@ export default function (pi) {
|
|
|
778
2347
|
return false;
|
|
779
2348
|
record.resultConsumed = true;
|
|
780
2349
|
cancelNudge(record.id);
|
|
2350
|
+
// Consumed is consumed: no deferred enrichment may ride the next
|
|
2351
|
+
// notification this record produces after a resume.
|
|
2352
|
+
deferredResultInterest.delete(record.id);
|
|
781
2353
|
return true;
|
|
782
2354
|
},
|
|
783
2355
|
},
|
|
@@ -796,15 +2368,15 @@ export default function (pi) {
|
|
|
796
2368
|
if (ctx.mode === "tui" && !mentionProviderRegistered) {
|
|
797
2369
|
mentionProviderRegistered = true;
|
|
798
2370
|
ctx.ui.addAutocompleteProvider(current => createMentionProvider(current,
|
|
799
|
-
// Plain text, not renderAgentName: the
|
|
800
|
-
//
|
|
2371
|
+
// Plain text, not renderAgentName: the widget's label, but autocomplete
|
|
2372
|
+
// descriptions cannot carry ANSI.
|
|
801
2373
|
() => mentionRoster(manager, mentionTypes(), type => getConfig(type).displayName), isAgentMentionsEnabled));
|
|
802
2374
|
}
|
|
803
2375
|
// Last, and only here: CLI flag values are applied by the host AFTER every
|
|
804
2376
|
// extension factory has run, so this is the earliest point the real value
|
|
805
2377
|
// exists. Detached inside — a workflow must not hold up session startup.
|
|
806
2378
|
resolveWorkflowCollisions(ctx);
|
|
807
|
-
runWorkflowFlag(ctx);
|
|
2379
|
+
await runWorkflowFlag(ctx);
|
|
808
2380
|
});
|
|
809
2381
|
/** Agent types `@` can start, in the shape the roster wants. */
|
|
810
2382
|
const mentionTypes = () => getAvailableTypes().map(name => ({ name, description: getAgentConfig(name)?.description ?? name }));
|
|
@@ -880,7 +2452,10 @@ export default function (pi) {
|
|
|
880
2452
|
// agent, so its frontmatter is what governs — `output_transcript: false`
|
|
881
2453
|
// must keep holding, since record.outputFile is the sole gate every
|
|
882
2454
|
// downstream consumer keys off and a resume must not re-open it.
|
|
883
|
-
|
|
2455
|
+
// Resolve from THIS refresh's registry, not the process-global one a
|
|
2456
|
+
// concurrent root may re-register while this hook is suspended.
|
|
2457
|
+
const registry = await reloadCustomAgentsAsync();
|
|
2458
|
+
const config = getAgentConfigIn(registry, record.type);
|
|
884
2459
|
const resumedRecord = await startBackgroundResume(ctx, record, mention.message, {
|
|
885
2460
|
outputTranscript: config?.outputTranscript ?? getOutputTranscriptDefault(),
|
|
886
2461
|
maxTurns: normalizeMaxTurns(config?.maxTurns ?? getDefaultMaxTurns()),
|
|
@@ -894,11 +2469,21 @@ export default function (pi) {
|
|
|
894
2469
|
}
|
|
895
2470
|
// Evicted, but its conversation is still on disk: reopen it. This is an
|
|
896
2471
|
// ordinary spawn carrying a session file, so the new record picks up the
|
|
897
|
-
// widget,
|
|
2472
|
+
// widget, transcript and completion notification unchanged —
|
|
898
2473
|
// and `reclaim` hands it back the names the tombstone was holding.
|
|
899
2474
|
if (resolved?.kind === "tombstone") {
|
|
900
2475
|
const entry = resolved.entry;
|
|
901
2476
|
const target = `@${entry.alias ?? entry.handle}`;
|
|
2477
|
+
// The original id's cleanup receipt may be unproven: the durable entry is
|
|
2478
|
+
// then neither a proven deletion nor a proven survivor. Reopening this
|
|
2479
|
+
// history under a NEW id would bypass the ids-only read barrier and could
|
|
2480
|
+
// replay a conversation whose saved report cleanup may already have
|
|
2481
|
+
// removed. Refuse before any new id, SDK session or history mutation —
|
|
2482
|
+
// including the drop-tombstone path below, which would forget it.
|
|
2483
|
+
if (cleanupUnprovenReports.has(entry.id)) {
|
|
2484
|
+
ctx.ui.notify(`Could not resume ${target} — cleanup removed this agent's previous report but could not verify the removal, so its saved history stays untouched until that receipt resolves.`, "warning");
|
|
2485
|
+
return { action: "handled" };
|
|
2486
|
+
}
|
|
902
2487
|
// Checked here rather than left to SessionManager.open: that runs inside
|
|
903
2488
|
// runAgent, whose rejection lands on the record as an agent error, not in
|
|
904
2489
|
// the catch below. A `/new` in another pi window or a manual delete makes
|
|
@@ -914,9 +2499,10 @@ export default function (pi) {
|
|
|
914
2499
|
// disabled type. A resume must not inherit that: reopening this
|
|
915
2500
|
// conversation under a different agent's prompt and tools is not
|
|
916
2501
|
// continuing it, and the new record would re-tombstone under the
|
|
917
|
-
// substitute, so the handle would never find its way back.
|
|
918
|
-
|
|
919
|
-
const
|
|
2502
|
+
// substitute, so the handle would never find its way back. Resolve from
|
|
2503
|
+
// THIS refresh's registry; a concurrent root may re-register the global.
|
|
2504
|
+
const scopedRegistry = await reloadCustomAgentsAsync();
|
|
2505
|
+
const dispatch = resolveSpawnTypeIn(scopedRegistry, entry.type);
|
|
920
2506
|
if (!dispatch.ok || dispatch.fellBackFrom !== undefined) {
|
|
921
2507
|
logSubagentIssue({ kind: "spawn_rejected", requestedType: entry.type,
|
|
922
2508
|
reason: dispatch.ok ? "Type now resolves only through fallbackSubagent; resume refused." : dispatch.message });
|
|
@@ -925,7 +2511,17 @@ export default function (pi) {
|
|
|
925
2511
|
ctx.ui.notify(`Could not resume ${target} — the ${entry.type} agent is no longer available.`, "warning");
|
|
926
2512
|
return { action: "handled" };
|
|
927
2513
|
}
|
|
2514
|
+
// Freeze the definition before the admission await: the conversation this
|
|
2515
|
+
// reopens must keep the prompt/tools/pins of the type that resolved here.
|
|
2516
|
+
const admittedDefinition = cloneAgentDefinition(getAgentConfigIn(scopedRegistry, dispatch.type));
|
|
928
2517
|
try {
|
|
2518
|
+
// A supported SDK host reaches this path without session_start, so the
|
|
2519
|
+
// root's lazy bind is its FIRST activation. Await that admission before
|
|
2520
|
+
// any new id or SDK history exists (spawnResolved re-proves it).
|
|
2521
|
+
const pendingAdmission = reportBindingAdmission(ctx);
|
|
2522
|
+
if (pendingAdmission !== undefined)
|
|
2523
|
+
await pendingAdmission;
|
|
2524
|
+
await assertCleanupRootAccessAsync(ctx.sessionManager?.getSessionId?.(), [entry.sessionFile]);
|
|
929
2525
|
// spawnResolved, not spawnTopLevel: the latter strips
|
|
930
2526
|
// `resumeSessionFile` and `reclaim` as untrusted. This path is the
|
|
931
2527
|
// exception — both come from a tombstone this extension wrote.
|
|
@@ -934,7 +2530,8 @@ export default function (pi) {
|
|
|
934
2530
|
reclaim: { handle: entry.handle, alias: entry.alias },
|
|
935
2531
|
resumeSessionFile: entry.sessionFile,
|
|
936
2532
|
isBackground: true,
|
|
937
|
-
|
|
2533
|
+
...(admittedDefinition === undefined ? {} : { agentDefinition: admittedDefinition }),
|
|
2534
|
+
}, true);
|
|
938
2535
|
// The agent may still be starting — wait, so a startup failure lands in
|
|
939
2536
|
// the catch below instead of being announced as a resume.
|
|
940
2537
|
await manager.awaitStartup(id);
|
|
@@ -960,6 +2557,20 @@ export default function (pi) {
|
|
|
960
2557
|
?? (alias ? resolveHandleToType(alias, getAvailableTypes()) : undefined);
|
|
961
2558
|
if (!type)
|
|
962
2559
|
return { action: "continue" };
|
|
2560
|
+
/**
|
|
2561
|
+
* Fresh scoped resolution and a frozen definition for a mention-started
|
|
2562
|
+
* type. The roster above is synchronous and may be stale; this refresh is
|
|
2563
|
+
* what the spawn is actually admitted with. FallbackSubagent is allowed
|
|
2564
|
+
* here, exactly as a model-initiated Agent call at the same moment would be.
|
|
2565
|
+
*/
|
|
2566
|
+
const admitMentionType = async () => {
|
|
2567
|
+
const registry = await reloadCustomAgentsAsync();
|
|
2568
|
+
const dispatch = resolveSpawnTypeIn(registry, type);
|
|
2569
|
+
if (!dispatch.ok)
|
|
2570
|
+
throw new Error(dispatch.message);
|
|
2571
|
+
const definition = cloneAgentDefinition(getAgentConfigIn(registry, dispatch.type));
|
|
2572
|
+
return { type: dispatch.type, ...(definition === undefined ? {} : { agentDefinition: definition }) };
|
|
2573
|
+
};
|
|
963
2574
|
// Claude Code never starts the agent itself: `@agent-<type>` becomes an
|
|
964
2575
|
// attachment asking the main model to do it, and the model writes the
|
|
965
2576
|
// agent's prompt from the conversation rather than forwarding the typed
|
|
@@ -991,10 +2602,19 @@ export default function (pi) {
|
|
|
991
2602
|
// agent the direct way rather than leaving the user with a toast and
|
|
992
2603
|
// nothing running.
|
|
993
2604
|
try {
|
|
994
|
-
|
|
2605
|
+
// Same first-activation admission as the direct path below. The
|
|
2606
|
+
// definition is frozen from this refresh before that await, so a
|
|
2607
|
+
// registry mutation while admission is pending cannot change it.
|
|
2608
|
+
const admitted = await admitMentionType();
|
|
2609
|
+
const pendingAdmission = reportBindingAdmission(ctx);
|
|
2610
|
+
if (pendingAdmission !== undefined)
|
|
2611
|
+
await pendingAdmission;
|
|
2612
|
+
await assertCleanupRootAccessAsync(ctx.sessionManager?.getSessionId?.());
|
|
2613
|
+
const id = spawnResolved(pi, ctx, admitted.type, mention.message, {
|
|
995
2614
|
description: describeMention(mention.message),
|
|
996
2615
|
isBackground: true,
|
|
997
|
-
|
|
2616
|
+
...(admitted.agentDefinition === undefined ? {} : { agentDefinition: admitted.agentDefinition }),
|
|
2617
|
+
}, true);
|
|
998
2618
|
// Same reason as the direct path below: the agent may still be
|
|
999
2619
|
// starting, and a failure there must reach this catch.
|
|
1000
2620
|
await manager.awaitStartup(id);
|
|
@@ -1003,19 +2623,29 @@ export default function (pi) {
|
|
|
1003
2623
|
catch (err) {
|
|
1004
2624
|
ctx.ui.notify(`Could not start ${label}: ${err instanceof Error ? err.message : String(err)}`, "error");
|
|
1005
2625
|
}
|
|
1006
|
-
})
|
|
2626
|
+
})
|
|
2627
|
+
// Last resort for the notify itself throwing (ctx gone stale): never an unhandled rejection.
|
|
2628
|
+
.catch((error) => console.warn("[pi-subagents] mention start failed:", error));
|
|
1007
2629
|
return { action: "handled" };
|
|
1008
2630
|
}
|
|
1009
2631
|
try {
|
|
1010
|
-
//
|
|
1011
|
-
//
|
|
1012
|
-
//
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
2632
|
+
// A supported SDK host can reach this start without session_start; the
|
|
2633
|
+
// root's first activation must be proven active before a new id exists.
|
|
2634
|
+
// The definition is frozen from this refresh BEFORE that await.
|
|
2635
|
+
const admitted = await admitMentionType();
|
|
2636
|
+
const pendingAdmission = reportBindingAdmission(ctx);
|
|
2637
|
+
if (pendingAdmission !== undefined)
|
|
2638
|
+
await pendingAdmission;
|
|
2639
|
+
await assertCleanupRootAccessAsync(ctx.sessionManager?.getSessionId?.());
|
|
2640
|
+
// Nothing else to pass: runAgent derives model, thinking and max turns
|
|
2641
|
+
// from the admitted definition, and the manager's onStart/onComplete
|
|
2642
|
+
// callbacks own the widget and completion notification — the same contract
|
|
2643
|
+
// the scheduler and cross-extension RPC spawns run under.
|
|
2644
|
+
const id = spawnResolved(pi, ctx, admitted.type, mention.message, {
|
|
1016
2645
|
description: describeMention(mention.message),
|
|
1017
2646
|
isBackground: true,
|
|
1018
|
-
|
|
2647
|
+
...(admitted.agentDefinition === undefined ? {} : { agentDefinition: admitted.agentDefinition }),
|
|
2648
|
+
}, true);
|
|
1019
2649
|
// The agent may still be starting (a worktree copy is an awaited git
|
|
1020
2650
|
// call) — report a failure that lands there as a failed start, not as a
|
|
1021
2651
|
// "Started" toast for an agent that never ran.
|
|
@@ -1028,7 +2658,9 @@ export default function (pi) {
|
|
|
1028
2658
|
return { action: "handled" };
|
|
1029
2659
|
});
|
|
1030
2660
|
pi.on("session_before_switch", () => {
|
|
2661
|
+
sessionEpoch++;
|
|
1031
2662
|
manager.clearCompleted(true);
|
|
2663
|
+
deferredResultInterest.clear();
|
|
1032
2664
|
scheduler.stop();
|
|
1033
2665
|
});
|
|
1034
2666
|
// The gap this whole feature closes: pi blanks the terminal spinner at
|
|
@@ -1053,6 +2685,11 @@ export default function (pi) {
|
|
|
1053
2685
|
// On shutdown, abort all agents immediately and clean up.
|
|
1054
2686
|
// If the session is going down, there's nothing left to consume agent results.
|
|
1055
2687
|
pi.on("session_shutdown", async () => {
|
|
2688
|
+
shuttingDown = true;
|
|
2689
|
+
sessionEpoch++;
|
|
2690
|
+
// Synchronous, before any await: no bus listener or steering ledger from
|
|
2691
|
+
// this binding may survive shutdown.
|
|
2692
|
+
goalBridge.unbind();
|
|
1056
2693
|
rpcHandle?.unsubSpawn();
|
|
1057
2694
|
rpcHandle?.unsubStop();
|
|
1058
2695
|
rpcHandle?.unsubPing();
|
|
@@ -1061,20 +2698,44 @@ export default function (pi) {
|
|
|
1061
2698
|
currentCtx = undefined;
|
|
1062
2699
|
// Only release the global slot if this activation claimed it — a child
|
|
1063
2700
|
// session's shutdown must not delete the root session's registry entry.
|
|
1064
|
-
if (ownsManagerRegistry &&
|
|
1065
|
-
delete
|
|
2701
|
+
if (ownsManagerRegistry && managerRegistryHost[MANAGER_KEY] === registryEntry) {
|
|
2702
|
+
delete managerRegistryHost[MANAGER_KEY];
|
|
1066
2703
|
}
|
|
1067
2704
|
scheduler.stop();
|
|
1068
2705
|
// Before abortAll, and not folded into it: a workflow owns a worker thread
|
|
1069
|
-
// as well as its children, and only its own signal terminates that.
|
|
2706
|
+
// as well as its children, and only its own signal terminates that. Maps and
|
|
2707
|
+
// creation/settlement proofs stay until quiescence is decided below: abort
|
|
2708
|
+
// is not proof that a workflow cannot still write.
|
|
1070
2709
|
for (const task of workflowTasks.values())
|
|
1071
2710
|
task.abortController.abort();
|
|
1072
|
-
workflowTasks.clear();
|
|
1073
2711
|
manager.abortAll();
|
|
1074
|
-
|
|
1075
|
-
|
|
2712
|
+
// Aborting stops a producer; it does NOT undo records the runtime already
|
|
2713
|
+
// accepted into its ordered write chain, nor the final artifact
|
|
2714
|
+
// registration and completion notification a settled run still owns. Wait
|
|
2715
|
+
// for the actual run promises and their accepted-journal tails, so a normal
|
|
2716
|
+
// process exit cannot drop resume history. The handles are re-read until
|
|
2717
|
+
// none remain: a launch already in flight can register after the first
|
|
2718
|
+
// pass. Bounded by the runs themselves (worker termination + accepted
|
|
2719
|
+
// appends), never by an arbitrary deadline.
|
|
2720
|
+
await awaitWorkflowQuiescence();
|
|
2721
|
+
// A workflow this shutdown stopped settled INSIDE the wait above, so its
|
|
2722
|
+
// completion is still held. Deliver that one notice now, synchronously:
|
|
2723
|
+
// its run is over and a held timer would only be cleared below. Nothing
|
|
2724
|
+
// can be scheduled AFTER the handler returns — every workflow id is marked
|
|
2725
|
+
// discarded here, and the remaining holds are agent notices, which have
|
|
2726
|
+
// never survived shutdown.
|
|
2727
|
+
flushStoppedWorkflowNudges();
|
|
2728
|
+
for (const id of new Set([
|
|
2729
|
+
...workflowTasks.keys(),
|
|
2730
|
+
...workflowRunPromises.keys(),
|
|
2731
|
+
...workflowJournalDrains.keys(),
|
|
2732
|
+
])) {
|
|
2733
|
+
discardedWorkflowNotifications.add(id);
|
|
2734
|
+
}
|
|
2735
|
+
for (const entry of pendingNudges.values())
|
|
2736
|
+
clearTimeout(entry.timer);
|
|
1076
2737
|
pendingNudges.clear();
|
|
1077
|
-
|
|
2738
|
+
deferredResultInterest.clear();
|
|
1078
2739
|
widget.dispose();
|
|
1079
2740
|
// Clear the terminal spinner before pi restores the terminal — nothing
|
|
1080
2741
|
// else writes the clear for work we asserted while the main session was
|
|
@@ -1084,32 +2745,80 @@ export default function (pi) {
|
|
|
1084
2745
|
// extensions bound there can release what they armed in `session_start` (#242).
|
|
1085
2746
|
// pi awaits this handler, and the process exits right after — unawaited, those
|
|
1086
2747
|
// handlers would never run. Internally bounded, so a hung one can't strand quit.
|
|
1087
|
-
await manager.dispose(pi);
|
|
2748
|
+
const shutdown = await manager.dispose(pi);
|
|
2749
|
+
// Lazy tool-only binding may still be creating a store not yet in the map.
|
|
2750
|
+
// Finish it before collecting stores, so its pending reports are flushed
|
|
2751
|
+
// and its activation cannot outlive this root's shutdown.
|
|
2752
|
+
await reportBindChain;
|
|
2753
|
+
// The manager has already handed every terminal/partial generation to its
|
|
2754
|
+
// root's store. Close EVERY bound root (a session switch may have left one
|
|
2755
|
+
// serving in-flight work): each close stops new saves, then drains accepted
|
|
2756
|
+
// writes/maintenance. Leases are released only for proven-quiescent stores
|
|
2757
|
+
// whose bounded drain completed; every uncertain root stays protected.
|
|
2758
|
+
const workflowWorkRemains = workflowCleanupProofs.size > 0
|
|
2759
|
+
|| [...workflowTasks.values()].some(task => task.status === "running" || task.status === "paused");
|
|
2760
|
+
const quiescent = shutdown.status === "completed" && !workflowWorkRemains;
|
|
2761
|
+
const stores = new Set([...reportStores.values(), reportStore]);
|
|
2762
|
+
await closeReportStores(stores, quiescent);
|
|
2763
|
+
// The lease decision above is final, and every workflow run/drain handle
|
|
2764
|
+
// was awaited above, so the maps are empty of live work by now. Clearing
|
|
2765
|
+
// them drops pointers, not work: nothing here is a substitute for the
|
|
2766
|
+
// drain. On an uncertain shutdown the proofs stay, exactly as before.
|
|
2767
|
+
workflowTasks.clear();
|
|
2768
|
+
workflowArtifactPaths.clear();
|
|
2769
|
+
workflowArtifactRoots.clear();
|
|
2770
|
+
workflowArtifactStores.clear();
|
|
2771
|
+
workflowCleanupProofs.clear();
|
|
2772
|
+
workflowRunPromises.clear();
|
|
2773
|
+
workflowJournalDrains.clear();
|
|
2774
|
+
knownGeneratedWorkflowPaths.clear();
|
|
2775
|
+
discardedWorkflowNotifications.clear();
|
|
2776
|
+
cleanupUnprovenReports.clear();
|
|
2777
|
+
// A later activation may reuse the same root id, but never its closed store.
|
|
2778
|
+
// Incomplete closes have already retained their leases above, so dropping
|
|
2779
|
+
// these object references cannot make an uncertain root look unprotected.
|
|
2780
|
+
reportStores.clear();
|
|
2781
|
+
reportActiveRoots.clear();
|
|
2782
|
+
if (archiveDrainTimer !== undefined) {
|
|
2783
|
+
clearTimeout(archiveDrainTimer);
|
|
2784
|
+
archiveDrainTimer = undefined;
|
|
2785
|
+
}
|
|
2786
|
+
archiveRetryAttempts.clear();
|
|
2787
|
+
pendingArchivedRecords.clear();
|
|
2788
|
+
reportBoundRoot = undefined;
|
|
2789
|
+
reportStore = createReportStore();
|
|
2790
|
+
reportBindChain = Promise.resolve();
|
|
1088
2791
|
});
|
|
1089
|
-
// Live widget
|
|
1090
|
-
// widgetMode (default "
|
|
2792
|
+
// Live compact widget; placement is independent of agent filtering.
|
|
2793
|
+
// widgetMode (default "all") selects what the widget shows: "all" =
|
|
1091
2794
|
// every agent; "background" = hide foreground (they already render inline as
|
|
1092
2795
|
// the Agent tool result, so showing them here too is a duplicate, #118), keep
|
|
1093
2796
|
// everything else; "off" = hide the widget entirely. Read live at render time.
|
|
1094
|
-
let widgetMode = "
|
|
2797
|
+
let widgetMode = "all";
|
|
1095
2798
|
function getWidgetMode() { return widgetMode; }
|
|
1096
|
-
|
|
2799
|
+
let widgetPlacement = "above";
|
|
2800
|
+
function getWidgetPlacement() { return widgetPlacement; }
|
|
2801
|
+
const widget = new AgentWidget(manager, agentActivity, getWidgetMode, isShowCostEnabled, isShowModelEnabled, getWidgetPlacement);
|
|
1097
2802
|
function setWidgetMode(m) { widgetMode = m; widget.update(); }
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
2803
|
+
function setWidgetPlacement(placement) { widgetPlacement = placement; widget.update(); }
|
|
2804
|
+
// ← opens the Hub whenever it would have rows: any top-level agent (running,
|
|
2805
|
+
// queued, or settled history awaiting the sweep) or a workflow run from this
|
|
2806
|
+
// session — regardless of what the widgetMode filter leaves visible in the
|
|
2807
|
+
// compact list. While the Hub is open it owns the keyboard (isOpen), so ←
|
|
2808
|
+
// can never stack a second overlay on top of it.
|
|
2809
|
+
let hubOpen = false;
|
|
2810
|
+
widget.setHubOpener({
|
|
2811
|
+
open: () => {
|
|
2812
|
+
if (!currentCtx)
|
|
2813
|
+
return;
|
|
2814
|
+
// Fire-and-forget from a key handler: a rejection here (for example a ctx gone stale) would end pi.
|
|
2815
|
+
void showFleetOverlay(currentCtx).catch((error) => {
|
|
2816
|
+
console.warn("[pi-subagents] could not open the agent hub:", error);
|
|
2817
|
+
});
|
|
2818
|
+
},
|
|
2819
|
+
hasContent: () => manager.listAgents().some(isTopLevelAgent) || (isWorkflowsEnabled() && fleetWorkflows().length > 0),
|
|
2820
|
+
isOpen: () => hubOpen,
|
|
1104
2821
|
});
|
|
1105
|
-
// ← at an empty prompt: the two-pane overlay (canonical roster surface — the
|
|
1106
|
-
// compact list stays the glanceable one). Between sessions there is no ctx to
|
|
1107
|
-
// open it against, and the key then stays with the editor.
|
|
1108
|
-
fleet.setOverlayOpener(() => { if (currentCtx)
|
|
1109
|
-
void showFleetOverlay(currentCtx); });
|
|
1110
|
-
let fleetViewEnabled = true;
|
|
1111
|
-
function isFleetViewEnabled() { return fleetViewEnabled; }
|
|
1112
|
-
function setFleetViewEnabled(b) { fleetViewEnabled = b; fleet.setEnabled(b); }
|
|
1113
2822
|
// Terminal spinner for background subagent work — the tab/taskbar progress
|
|
1114
2823
|
// pi clears at agent_end even when subagents keep running. See
|
|
1115
2824
|
// terminal-progress.ts for the ownership rules (pi owns the indicator while
|
|
@@ -1176,6 +2885,22 @@ export default function (pi) {
|
|
|
1176
2885
|
workflowsEnabled = b;
|
|
1177
2886
|
workflowsPinned = true;
|
|
1178
2887
|
}
|
|
2888
|
+
// Agent type a workflow's `agent()` call uses when it names none. `task` is
|
|
2889
|
+
// the economical default (DEFAULT_WORKFLOW_AGENT_TYPE in runtime.ts); this
|
|
2890
|
+
// setting pins a different role per project. Precedence is per-run: an
|
|
2891
|
+
// explicit `SubagentWorkflow(agentType)` outranks it, a resume inherits the
|
|
2892
|
+
// original run's frozen choice, and a script's per-call `opts.agentType`
|
|
2893
|
+
// outranks all three. Read live when a run is created — existing tasks keep
|
|
2894
|
+
// the role they started with, so changing the setting never re-roles a run
|
|
2895
|
+
// already in flight.
|
|
2896
|
+
//
|
|
2897
|
+
// Deliberately not validated against the registry here: a role can be renamed
|
|
2898
|
+
// or temporarily disabled, and silently substituting a different (possibly
|
|
2899
|
+
// expensive) role would hide that. Resolution stays at spawn time, where an
|
|
2900
|
+
// unavailable workflow default is refused rather than sent to a fallback.
|
|
2901
|
+
let workflowDefaultAgentType = DEFAULT_WORKFLOW_AGENT_TYPE;
|
|
2902
|
+
function getWorkflowDefaultAgentType() { return workflowDefaultAgentType; }
|
|
2903
|
+
function setWorkflowDefaultAgentType(agentType) { workflowDefaultAgentType = agentType; }
|
|
1179
2904
|
// ---- Disable default agents configuration ----
|
|
1180
2905
|
// When enabled, the three hardcoded default agents (general-purpose, Explore,
|
|
1181
2906
|
// Plan) are not registered. User-defined agents from project/global custom
|
|
@@ -1239,7 +2964,7 @@ export default function (pi) {
|
|
|
1239
2964
|
/**
|
|
1240
2965
|
* Launch a detached resume of an existing agent and wire everything a
|
|
1241
2966
|
* re-running agent needs: transcript anchoring, activity tracking, join-mode
|
|
1242
|
-
* batching, the widget
|
|
2967
|
+
* batching, the widget refresh, and the `subagents:created` event.
|
|
1243
2968
|
*
|
|
1244
2969
|
* Shared by the Agent tool's `resume` + `run_in_background` branch and the
|
|
1245
2970
|
* `@handle message` prompt mention — they differ only in how they report the
|
|
@@ -1249,30 +2974,27 @@ export default function (pi) {
|
|
|
1249
2974
|
* Callers must have already established that the record has a session.
|
|
1250
2975
|
*/
|
|
1251
2976
|
async function startBackgroundResume(ctx, existing, prompt, opts) {
|
|
2977
|
+
// Before the first record/transcript mutation: a selected id/session or a
|
|
2978
|
+
// root reserved by cleanup must never reopen work on the artifact set. The
|
|
2979
|
+
// combined async scope covers the agent, its session and its transcript;
|
|
2980
|
+
// the entering root is proved separately when it is not the record's own.
|
|
2981
|
+
await assertCleanupArtifactAccessAsync(existing);
|
|
2982
|
+
const enteringRoot = ctx.sessionManager.getSessionId();
|
|
2983
|
+
if (existing.rootSessionId === undefined || existing.rootSessionId !== enteringRoot) {
|
|
2984
|
+
await assertCleanupRootAccessAsync(enteringRoot, [existing.sessionFile]);
|
|
2985
|
+
}
|
|
1252
2986
|
const id = existing.id;
|
|
1253
2987
|
const joinMode = resolveJoinMode(defaultJoinMode, true);
|
|
1254
|
-
|
|
1255
|
-
//
|
|
1256
|
-
//
|
|
1257
|
-
//
|
|
1258
|
-
|
|
1259
|
-
if (joinMode)
|
|
1260
|
-
existing.joinMode = joinMode;
|
|
1261
|
-
// Reuse the agent's transcript rather than starting a fresh one: the
|
|
1262
|
-
// path is deterministic per agent+session, so writing an initial entry
|
|
1263
|
-
// would truncate the previous run's turns (see ensureOutputFile).
|
|
1264
|
-
if (opts.outputTranscript) {
|
|
1265
|
-
existing.outputFile = createOutputFilePath(ctx.cwd, id, ctx.sessionManager.getSessionId());
|
|
1266
|
-
ensureOutputFile(existing.outputFile);
|
|
1267
|
-
}
|
|
1268
|
-
// Anchor streaming past the turns already on disk, captured BEFORE the
|
|
1269
|
-
// run starts. The resumed prompt lands as an ordinary user message at
|
|
1270
|
-
// this index, so it is written exactly once.
|
|
1271
|
-
const transcriptAnchor = existing.session?.messages.length ?? 0;
|
|
2988
|
+
const outputSessionId = ctx.sessionManager.getSessionId();
|
|
2989
|
+
// Pure locals only: nothing shared is touched until the manager says this
|
|
2990
|
+
// caller won admission. The tracker is created here so the synchronous
|
|
2991
|
+
// `onAdmitted` hook allocates nothing that could throw mid-transition; the
|
|
2992
|
+
// anchor is captured by the hook, from the record the accepted run owns.
|
|
1272
2993
|
const { state: bgState, callbacks: bgCallbacks } = createActivityTracker(opts.maxTurns);
|
|
1273
2994
|
// resumeAgent has no onSessionCreated — the session predates this run —
|
|
1274
2995
|
// so seed it directly, or the widget shows no context % for the agent.
|
|
1275
2996
|
bgState.session = existing.session;
|
|
2997
|
+
let transcriptAnchor = 0;
|
|
1276
2998
|
// No `signal`: a background spawn deliberately omits it, and a detached
|
|
1277
2999
|
// resume must behave the same. Passing it would abort this agent when
|
|
1278
3000
|
// the parent turn is interrupted (user Esc), while agents started with
|
|
@@ -1281,10 +3003,37 @@ export default function (pi) {
|
|
|
1281
3003
|
isBackground: true,
|
|
1282
3004
|
onToolActivity: bgCallbacks.onToolActivity,
|
|
1283
3005
|
onAssistantUsage: bgCallbacks.onAssistantUsage,
|
|
3006
|
+
// The ownership boundary. The manager runs this synchronously only for
|
|
3007
|
+
// the WINNING resume, after its last guarded identity check and before
|
|
3008
|
+
// any generation/terminal/start bookkeeping. Everything shared and
|
|
3009
|
+
// caller-visible is mutated here, so a refused concurrent caller cannot
|
|
3010
|
+
// rewrite the winner's tool-call correlation, join mode, output wiring
|
|
3011
|
+
// or anchor. Only accepted ownership can reach the record's own fields.
|
|
3012
|
+
onAdmitted: admitted => {
|
|
3013
|
+
// Assigned unconditionally: the completion notification carries this as
|
|
3014
|
+
// `<tool-use-id>`, so a mention-resume (which passes none) has to CLEAR
|
|
3015
|
+
// the id left by the spawn that created the record. Keeping it would
|
|
3016
|
+
// point the orchestrator's new result at a tool call that was answered
|
|
3017
|
+
// runs ago.
|
|
3018
|
+
admitted.toolCallId = opts.toolCallId;
|
|
3019
|
+
if (joinMode)
|
|
3020
|
+
admitted.joinMode = joinMode;
|
|
3021
|
+
// Reuse the agent's transcript rather than starting a fresh one: the
|
|
3022
|
+
// path is deterministic per agent+session, so writing an initial entry
|
|
3023
|
+
// would truncate the previous run's turns (see ensureOutputFile).
|
|
3024
|
+
if (opts.outputTranscript) {
|
|
3025
|
+
admitted.outputFile = createOutputFilePath(ctx.cwd, id, outputSessionId);
|
|
3026
|
+
ensureOutputFile(admitted.outputFile);
|
|
3027
|
+
}
|
|
3028
|
+
// Anchor streaming past the turns already on disk, captured BEFORE the
|
|
3029
|
+
// run starts. The resumed prompt lands as an ordinary user message at
|
|
3030
|
+
// this index, so it is written exactly once.
|
|
3031
|
+
transcriptAnchor = admitted.session?.messages.length ?? 0;
|
|
3032
|
+
},
|
|
1284
3033
|
// Fires when the run actually starts — immediately, or on queue
|
|
1285
3034
|
// drain. Wiring it here (rather than after resume() returns) means a
|
|
1286
|
-
// resume stopped while still queued never started streaming, so
|
|
1287
|
-
//
|
|
3035
|
+
// resume stopped while still queued never started streaming, so there
|
|
3036
|
+
// is no subscription left behind for a later run to trip over.
|
|
1288
3037
|
onStarted: () => {
|
|
1289
3038
|
const rec = manager.getRecord(id);
|
|
1290
3039
|
if (rec?.session && rec.outputFile) {
|
|
@@ -1294,6 +3043,9 @@ export default function (pi) {
|
|
|
1294
3043
|
});
|
|
1295
3044
|
if (!record)
|
|
1296
3045
|
return undefined;
|
|
3046
|
+
// Deliberately NOT cleared here: `store.save` refuses to replace an existing
|
|
3047
|
+
// deletion receipt, so a resume starting proves nothing about the durable
|
|
3048
|
+
// body. Only a durably saved full entry clears the barrier (saveArchivedRecord).
|
|
1297
3049
|
if (joinMode != null && joinMode !== 'async') {
|
|
1298
3050
|
currentBatchAgents.push({ id, joinMode });
|
|
1299
3051
|
if (batchFinalizeTimer)
|
|
@@ -1307,8 +3059,6 @@ export default function (pi) {
|
|
|
1307
3059
|
widget.markRunning(id);
|
|
1308
3060
|
widget.ensureTimer();
|
|
1309
3061
|
widget.update();
|
|
1310
|
-
fleet.ensureTimer();
|
|
1311
|
-
fleet.update();
|
|
1312
3062
|
// Resume ignores subagent_type (the record keeps the type it was
|
|
1313
3063
|
// spawned with), so report the record's own identity — a "created"
|
|
1314
3064
|
// event carrying the caller's type would re-register the agent under
|
|
@@ -1324,7 +3074,6 @@ export default function (pi) {
|
|
|
1324
3074
|
// Grab UI context from first tool execution + clear lingering widget on new turn
|
|
1325
3075
|
pi.on("tool_execution_start", async (_event, ctx) => {
|
|
1326
3076
|
widget.setUICtx(ctx.ui);
|
|
1327
|
-
fleet.setUICtx(ctx.ui);
|
|
1328
3077
|
widget.onTurnStart();
|
|
1329
3078
|
});
|
|
1330
3079
|
/** Build the full type list text dynamically from available agents only. */
|
|
@@ -1363,6 +3112,9 @@ export default function (pi) {
|
|
|
1363
3112
|
setMaxConcurrentForeground: (n) => manager.setMaxConcurrentForeground(n),
|
|
1364
3113
|
setDefaultMaxTurns,
|
|
1365
3114
|
setGraceTurns,
|
|
3115
|
+
// Caller turn caps are a policy, so this one is not merely persisted: a
|
|
3116
|
+
// project/session that omits the key must not inherit another's `true`.
|
|
3117
|
+
setAllowPerCallTurnLimits,
|
|
1366
3118
|
setDefaultJoinMode,
|
|
1367
3119
|
setBackgroundByDefault,
|
|
1368
3120
|
setSchedulingEnabled,
|
|
@@ -1370,13 +3122,14 @@ export default function (pi) {
|
|
|
1370
3122
|
setStrictAgentFiles: (b) => { strictAgentFiles = b; },
|
|
1371
3123
|
setDisableDefaultAgents: setDisableDefaultAgents,
|
|
1372
3124
|
setToolDescriptionMode: setToolDescriptionMode,
|
|
1373
|
-
setFleetView: setFleetViewEnabled,
|
|
1374
3125
|
setAgentMentions: setAgentMentionMode,
|
|
1375
3126
|
setRememberAgents,
|
|
1376
3127
|
setWidgetMode: setWidgetMode,
|
|
3128
|
+
setWidgetPlacement,
|
|
1377
3129
|
setOutputTranscript: setOutputTranscriptDefault,
|
|
1378
3130
|
setWorktreeIsolation: setWorktreeIsolationEnabled,
|
|
1379
3131
|
setWorkflowsEnabled: setWorkflowsEnabled,
|
|
3132
|
+
setWorkflowDefaultAgentType: setWorkflowDefaultAgentType,
|
|
1380
3133
|
setMaxSubagentDepth: setMaxSubagentDepth,
|
|
1381
3134
|
setFallbackSubagent: setFallbackSubagent,
|
|
1382
3135
|
setReportUsage,
|
|
@@ -1429,15 +3182,15 @@ export default function (pi) {
|
|
|
1429
3182
|
// Compact Agent tool description (#91, `toolDescriptionMode: "compact"`) —
|
|
1430
3183
|
// the same load-bearing facts as the full version at ~75% fewer tokens, for
|
|
1431
3184
|
// small/local models. Per-option details live in the param descriptions.
|
|
1432
|
-
const compactAgentToolDescription = `Launch an autonomous agent
|
|
3185
|
+
const compactAgentToolDescription = `Launch an autonomous agent. Types:
|
|
1433
3186
|
${buildCompactTypeListText()}
|
|
1434
3187
|
|
|
1435
|
-
Custom agents: .pi/agents/<name>.md (project) or
|
|
3188
|
+
Custom agents: .pi/agents/<name>.md (project), or agents/<name>.md under the configured pi agent directory (global).
|
|
1436
3189
|
|
|
1437
3190
|
Notes:
|
|
1438
|
-
- description: 3-5 words
|
|
3191
|
+
- description: 3-5 UI words. Prompts must be self-contained; the agent hasn't seen this conversation.
|
|
1439
3192
|
- Parallel work: one message, multiple Agent calls — they run concurrently.
|
|
1440
|
-
- Subagents run in the background by default; you'll be notified when one completes. Pass run_in_background: false
|
|
3193
|
+
- Subagents run in the background by default; you'll be notified when one completes. Pass run_in_background: false when your very next action depends on the result. In the terminal UI that is a PENDING logical await — your turn is released and the report arrives in a later turn; headless/print runs block inline. Never poll for, fabricate, or predict a pending agent's result.
|
|
1441
3194
|
- The result is not shown to the user — summarize it for them. Verify an agent's claimed code changes before reporting work done.
|
|
1442
3195
|
- resume continues a previous agent by ID. If the user asks to cancel/stop an agent, call stop_subagent; to redirect it, call steer_subagent.${isolationCompactGuideline}`;
|
|
1443
3196
|
const fullAgentToolDescription = `Launch a new agent to handle complex, multi-step tasks autonomously. Each agent type has specific capabilities and tools available to it.
|
|
@@ -1459,8 +3212,8 @@ If the target is already known, use a direct tool — \`read\` for a known path,
|
|
|
1459
3212
|
- When you launch multiple agents for independent work, send them in a single message with multiple tool uses so they run concurrently. If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Agent tool use content blocks.
|
|
1460
3213
|
- When the agent is done, it returns a single message back to you. The result is not visible to the user — to show the user, send a text message with a concise summary.
|
|
1461
3214
|
- Trust but verify: an agent's summary describes what it intended to do, not necessarily what it did. When an agent writes or edits code, check the actual changes before reporting the work as done.
|
|
1462
|
-
- Agents run in the background by default. When an agent runs in the background, you will be automatically notified when it completes — do NOT sleep, poll, or proactively check on its progress. Continue with other work or respond to the user instead.
|
|
1463
|
-
- **Foreground vs background**: Pass \`run_in_background: false\` only when your very next action depends on the agent's result and nothing else could usefully happen while it runs — e.g., a research agent whose finding gates the edit you're about to make. Otherwise let it run in the background (the default) — this includes fire-and-forget work, independent investigations, and anything where the user might hand you something else in the meantime. Wanting the result "next" is not enough on its own.
|
|
3215
|
+
- Agents run in the background by default. When an agent runs in the background, you will be automatically notified when it completes, and that notification carries the agent's complete final report — do NOT sleep, poll, or proactively check on its progress. Continue with other work or respond to the user instead.
|
|
3216
|
+
- **Foreground vs background**: Pass \`run_in_background: false\` only when your very next action depends on the agent's result and nothing else could usefully happen while it runs — e.g., a research agent whose finding gates the edit you're about to make. Otherwise let it run in the background (the default) — this includes fire-and-forget work, independent investigations, and anything where the user might hand you something else in the meantime. Wanting the result "next" is not enough on its own. In the terminal UI a foreground request is a logical await anyway: it returns PENDING immediately and releases your turn, and the agent's complete final report arrives automatically in a later turn (headless/print runs still block inline).
|
|
1464
3217
|
- **Don't race**: after launching a background agent, you know nothing about its results. Never fabricate or predict them in any format — not as prose, summary, or structured output. The completion notification arrives in a later turn; it is never something you write yourself. If the user asks before it lands, say the agent is still running — give status, not a guess.
|
|
1465
3218
|
- Use resume with an agent ID to continue a previous agent's work. A new (non-resume) Agent call starts a fresh agent with no memory of prior runs, so the prompt must be self-contained.
|
|
1466
3219
|
- Use steer_subagent to send mid-run messages to a running background agent.
|
|
@@ -1547,7 +3300,7 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1547
3300
|
"Use Agent with specialized agents when the task matches an agent type's description. Subagents are valuable for parallelizing independent queries or for protecting the main context window from excessive results, but should not be used excessively when not needed. Importantly, avoid duplicating work that subagents are already doing — if you delegate research to a subagent, do not also perform the same searches yourself.",
|
|
1548
3301
|
`Use Agent by choosing the required subagent_type from the enabled roles and their descriptions.${rolePreferences.length ? ` Prefer ${rolePreferences.join("; ")}.` : ""} Use exact names, including case. Explicit valid choices remain authoritative; there is no automatic task classifier or forced remapping. For a known target, use direct tools (read, grep, find).`,
|
|
1549
3302
|
"Agent model and thinking pins take precedence over call parameters. Unpinned fields use caller parameters, otherwise inherit the live parent model and thinking level. inherit_context controls conversation history, not model selection.",
|
|
1550
|
-
"When an agent runs in the background, you will be notified on completion
|
|
3303
|
+
"When an agent runs in the background — including a run_in_background: false request in the terminal UI, which returns PENDING at once and releases your turn — you will be notified on completion, and that notification carries the agent's complete final report. Do not poll or sleep waiting for it, never fabricate a pending result, and keep continuing with useful work instead. A sibling tool in the same batch may proceed without the dependency's result; it is not complete yet.",
|
|
1551
3304
|
"Trust but verify: an agent's summary describes intent, not outcome. When an agent writes or edits code, check the actual changes before reporting work as done.",
|
|
1552
3305
|
],
|
|
1553
3306
|
parameters: Type.Object({
|
|
@@ -1569,15 +3322,16 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1569
3322
|
thinking: Type.Optional(Type.String({
|
|
1570
3323
|
description: `Thinking level: ${THINKING_LEVELS.join(", ")}. Agent thinking pin wins; this parameter only fills an unspecified field. Omit to inherit live parent thinking when unpinned.`,
|
|
1571
3324
|
})),
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
3325
|
+
// Caller turn caps are a configurable policy (off by default): when
|
|
3326
|
+
// disabled the parameter is absent from the schema entirely, so the model
|
|
3327
|
+
// is never offered a knob the resolver would drop. Runtime filtering
|
|
3328
|
+
// still covers calls that bypass schema validation.
|
|
3329
|
+
...maxTurnsParam(getAllowPerCallTurnLimits()),
|
|
1576
3330
|
run_in_background: Type.Optional(Type.Boolean({
|
|
1577
|
-
description: "Defaults to true — the agent runs detached, returning its ID immediately, and you are notified on completion. Set false
|
|
3331
|
+
description: "Defaults to true — the agent runs detached, returning its ID immediately, and you are notified on completion. Set false when your very next action depends on the result. In the terminal UI (interactive mode), false is a logical await: the call returns PENDING immediately and releases your turn, the agent keeps running in the background, and its complete final report arrives automatically in a later turn — do not poll or fabricate it. In headless/print runs, false keeps the historical inline contract: the call blocks and returns the agent's full output inline.",
|
|
1578
3332
|
})),
|
|
1579
3333
|
resume: Type.Optional(Type.String({
|
|
1580
|
-
description: "Optional agent ID to resume from. Continues from previous context. Resumes detached like any other spawn; pass run_in_background: false to block and
|
|
3334
|
+
description: "Optional agent ID to resume from. Continues from previous context. Resumes detached like any other spawn; pass run_in_background: false to request foreground — in the terminal UI that returns PENDING at once and the complete report arrives in a later turn, while headless/print runs block and return it inline. An agent can only be resumed once its current run has finished — use steer_subagent to reach one mid-run.",
|
|
1581
3335
|
})),
|
|
1582
3336
|
isolated: Type.Optional(Type.Boolean({
|
|
1583
3337
|
description: "If true, agent gets no extension/MCP tools — only built-in tools.",
|
|
@@ -1701,17 +3455,32 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1701
3455
|
},
|
|
1702
3456
|
// ---- Execute ----
|
|
1703
3457
|
execute: async (toolCallId, params, signal, onUpdate, ctx) => {
|
|
3458
|
+
// First tool may run without a prior session_start (older harnesses).
|
|
3459
|
+
// Start the bind but do not await it here: the Agent tool's dispatch must
|
|
3460
|
+
// stay synchronous so two blocking calls in one pi batch still reach the
|
|
3461
|
+
// foreground queue in the same tick. session_start has already bound the
|
|
3462
|
+
// real session before any tool runs. A root this command is about to
|
|
3463
|
+
// delete is not bound at all — binding publishes a lease and runs
|
|
3464
|
+
// maintenance — so only that case skips the eager bind; an inactive
|
|
3465
|
+
// (refused) binding still retries, which is how it recovers a released
|
|
3466
|
+
// foreign lock, and the artifact guard below refuses work until it has.
|
|
3467
|
+
const initialAgentRoot = ctx.sessionManager?.getSessionId?.();
|
|
3468
|
+
if (!cleanupRootReserved(initialAgentRoot))
|
|
3469
|
+
void ensureReportBinding(ctx);
|
|
1704
3470
|
// Ensure we have UI context for widget rendering
|
|
1705
3471
|
widget.setUICtx(ctx.ui);
|
|
1706
|
-
//
|
|
1707
|
-
|
|
3472
|
+
// Awaitable refresh: new project/global .md files are picked up without a
|
|
3473
|
+
// restart, and dispatch resolves against THIS load's registry. The
|
|
3474
|
+
// process-global registry can be re-registered by a concurrent root while
|
|
3475
|
+
// this call suspends, so it is not consulted after the await.
|
|
3476
|
+
const registry = await reloadCustomAgentsAsync();
|
|
1708
3477
|
const rawType = params.subagent_type;
|
|
1709
3478
|
// Single decision point for dispatch (#183): unknown, disabled and
|
|
1710
3479
|
// case-ambiguous types are refused here, BEFORE anything spawns, so a
|
|
1711
3480
|
// background or scheduled call can't start running the wrong agent while
|
|
1712
3481
|
// the caller is still unaware. `fallbackSubagent` decides whether an
|
|
1713
3482
|
// unresolvable type falls back or fails closed.
|
|
1714
|
-
const dispatch =
|
|
3483
|
+
const dispatch = resolveSpawnTypeIn(registry, rawType);
|
|
1715
3484
|
// `resume` replays a stored session and ignores `subagent_type` entirely,
|
|
1716
3485
|
// but the parameter is required by the schema — so gating it here would
|
|
1717
3486
|
// make a live agent unresumable the moment its type is deleted, disabled,
|
|
@@ -1731,15 +3500,28 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1731
3500
|
// session and ignores `subagent_type` entirely, so a note about type
|
|
1732
3501
|
// substitution would be describing something that didn't happen.
|
|
1733
3502
|
const fallbackNote = dispatch.ok && dispatch.fellBackFrom !== undefined
|
|
1734
|
-
? `Note: Unknown agent type "${dispatch.fellBackFrom}" — using ${
|
|
3503
|
+
? `Note: Unknown agent type "${dispatch.fellBackFrom}" — using ${getAgentConfigIn(registry, subagentType) ? subagentType : "the fallback agent config"}.\n\n`
|
|
1735
3504
|
: "";
|
|
1736
3505
|
const displayName = getDisplayName(subagentType);
|
|
1737
|
-
// Get agent config
|
|
1738
|
-
|
|
3506
|
+
// Get agent config from the SAME registry that resolved the type, then
|
|
3507
|
+
// freeze it before any report-admission/worktree await. Queueing, a slow
|
|
3508
|
+
// guard or a reload in another root must not change the prompt, tool
|
|
3509
|
+
// permissions, model or nesting policy this call was admitted with.
|
|
3510
|
+
const customConfig = getAgentConfigIn(registry, subagentType);
|
|
3511
|
+
const admittedDefinition = cloneAgentDefinition(customConfig);
|
|
1739
3512
|
const resolvedConfig = resolveAgentInvocationConfig(customConfig, params, {
|
|
1740
3513
|
worktreeAllowed: isWorktreeIsolationEnabled(),
|
|
1741
3514
|
defaultRunInBackground: getBackgroundByDefault(),
|
|
3515
|
+
// Caller caps are opt-in: with the policy off, a `max_turns` parameter
|
|
3516
|
+
// is dropped here (the schema also omits it), while an agent-file pin
|
|
3517
|
+
// and the configured default keep deciding the real budget.
|
|
3518
|
+
allowPerCallTurnLimits: getAllowPerCallTurnLimits(),
|
|
1742
3519
|
});
|
|
3520
|
+
// `/subagents off`: the spawn twins the main model — pins and caller
|
|
3521
|
+
// overrides give way, and a scope check against the model the session is
|
|
3522
|
+
// already running can only produce a spurious refusal. Resume is left
|
|
3523
|
+
// alone either way: it replays the stored session, model included.
|
|
3524
|
+
const twinForced = isForceMainModel();
|
|
1743
3525
|
// Resume keeps the existing session's model; validate only new spawns.
|
|
1744
3526
|
// Caller shorthand retains resolveModel's policy. A qualified agent pin
|
|
1745
3527
|
// resolves exactly, then to the same id on another available provider;
|
|
@@ -1747,7 +3529,7 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1747
3529
|
// visible notice, while user-authored pins stay strict and throw.
|
|
1748
3530
|
let model = ctx.model;
|
|
1749
3531
|
let pinFallbackNotice;
|
|
1750
|
-
if (!params.resume && resolvedConfig.modelInput !== undefined) {
|
|
3532
|
+
if (!twinForced && !params.resume && resolvedConfig.modelInput !== undefined) {
|
|
1751
3533
|
const resolved = resolvedConfig.modelFromParams
|
|
1752
3534
|
? resolveModel(resolvedConfig.modelInput, ctx.modelRegistry)
|
|
1753
3535
|
: resolvePinnedModel(resolvedConfig.modelInput, ctx.modelRegistry, {
|
|
@@ -1772,20 +3554,22 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1772
3554
|
// Scope validation: the effective resolved model is checked against the
|
|
1773
3555
|
// user's enabledModels list. Policy (hard error vs warn-and-proceed) lives
|
|
1774
3556
|
// in model-scope.ts so the nested delegation tools apply the same rule.
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
3557
|
+
if (!twinForced) {
|
|
3558
|
+
const scopeVerdict = checkModelScope({
|
|
3559
|
+
model,
|
|
3560
|
+
cwd: ctx.cwd,
|
|
3561
|
+
modelRegistry: ctx.modelRegistry,
|
|
3562
|
+
callerSupplied: resolvedConfig.modelFromParams,
|
|
3563
|
+
agentLabel: customConfig?.displayName ?? subagentType,
|
|
3564
|
+
modelInput: resolvedConfig.modelInput,
|
|
3565
|
+
});
|
|
3566
|
+
if (!params.resume && scopeVerdict.kind === "error") {
|
|
3567
|
+
logSubagentIssue({ kind: "spawn_rejected", requestedType: subagentType, reason: scopeVerdict.message });
|
|
3568
|
+
return textResult(scopeVerdict.message);
|
|
3569
|
+
}
|
|
3570
|
+
if (!params.resume && scopeVerdict.kind === "warn")
|
|
3571
|
+
ctx.ui.notify(scopeVerdict.message, "warning");
|
|
1786
3572
|
}
|
|
1787
|
-
if (!params.resume && scopeVerdict.kind === "warn")
|
|
1788
|
-
ctx.ui.notify(scopeVerdict.message, "warning");
|
|
1789
3573
|
const thinking = resolvedConfig.thinking;
|
|
1790
3574
|
const inheritContext = resolvedConfig.inheritContext;
|
|
1791
3575
|
const runInBackground = resolvedConfig.runInBackground;
|
|
@@ -1809,9 +3593,10 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1809
3593
|
// This is the pre-session snapshot — agent-manager overwrites it with the
|
|
1810
3594
|
// effective values the moment a session reports them.
|
|
1811
3595
|
const { modelName, modelId } = model ? describeModel(model) : { modelName: undefined, modelId: undefined };
|
|
1812
|
-
const modelSource = resolvedConfig.modelInput
|
|
1813
|
-
:
|
|
1814
|
-
:
|
|
3596
|
+
const modelSource = twinForced ? `forced to the main model (/subagents off)${resolvedConfig.modelInput !== undefined ? `; "${resolvedConfig.modelInput}" ignored` : ""}`
|
|
3597
|
+
: resolvedConfig.modelInput === undefined ? "parent inheritance; unpinned"
|
|
3598
|
+
: pinFallbackNotice !== undefined ? `agent pin "${resolvedConfig.modelInput}" unavailable; parent model substituted`
|
|
3599
|
+
: `${resolvedConfig.modelFromParams ? "caller" : "agent pin"}: "${resolvedConfig.modelInput}"`;
|
|
1815
3600
|
const thinkingSource = customConfig?.thinking !== undefined ? `agent pin: "${customConfig.thinking}"`
|
|
1816
3601
|
: params.thinking !== undefined ? `caller: "${params.thinking}"` : "parent inheritance; unpinned";
|
|
1817
3602
|
const selectionNoteFor = (record) => {
|
|
@@ -1910,7 +3695,7 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1910
3695
|
return textResult("Scheduler is not active in this session yet. Try again after the session has fully started.");
|
|
1911
3696
|
}
|
|
1912
3697
|
try {
|
|
1913
|
-
const job = scheduler.addJob({
|
|
3698
|
+
const job = await scheduler.addJob({
|
|
1914
3699
|
name: params.description,
|
|
1915
3700
|
description: params.description,
|
|
1916
3701
|
schedule: params.schedule,
|
|
@@ -1933,6 +3718,26 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1933
3718
|
return textResult(err instanceof Error ? err.message : String(err));
|
|
1934
3719
|
}
|
|
1935
3720
|
}
|
|
3721
|
+
// Schedule definitions and settings are not cleanup artifacts. Every
|
|
3722
|
+
// path below can create a session/output/artifact, so guard it here.
|
|
3723
|
+
const agentRootSessionId = ctx.sessionManager.getSessionId();
|
|
3724
|
+
// Await this root's own binding admission — including the FIRST persistent
|
|
3725
|
+
// activation a supported SDK host reaches without session_start — and then
|
|
3726
|
+
// prove it is active before any session/output/worktree exists. An active
|
|
3727
|
+
// root returns without yielding (same-tick batch); an intentional
|
|
3728
|
+
// ephemeral context keeps its deferred-bind contract.
|
|
3729
|
+
const pendingAdmission = reportBindingAdmission(ctx);
|
|
3730
|
+
if (pendingAdmission !== undefined)
|
|
3731
|
+
await pendingAdmission;
|
|
3732
|
+
// Await the owning store's activation/root lock and any selected-path
|
|
3733
|
+
// lock through the async scan, then re-check this command's reservations
|
|
3734
|
+
// synchronously as the last step. Previously this was a synchronous full
|
|
3735
|
+
// scan; an SDK host that reaches this point through an await must not
|
|
3736
|
+
// block the main thread on every foreign root's lock metadata.
|
|
3737
|
+
await assertCleanupRootAccessAsync(agentRootSessionId);
|
|
3738
|
+
// Fail closed when the awaited bind threw or was refused: an absent store
|
|
3739
|
+
// makes the acquisition guard above a no-op, and that is not permission.
|
|
3740
|
+
assertReportBindingAdmission(ctx);
|
|
1936
3741
|
// Resume existing agent
|
|
1937
3742
|
if (params.resume) {
|
|
1938
3743
|
const existing = manager.getRecord(params.resume);
|
|
@@ -1942,11 +3747,13 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1942
3747
|
if (!existing.session) {
|
|
1943
3748
|
return textResult(`Agent "${params.resume}" has no active session to resume.`);
|
|
1944
3749
|
}
|
|
1945
|
-
//
|
|
1946
|
-
//
|
|
1947
|
-
//
|
|
1948
|
-
//
|
|
1949
|
-
|
|
3750
|
+
// A resume that hands control back: either an explicit background
|
|
3751
|
+
// call, or an interactive foreground request, which is a logical await
|
|
3752
|
+
// in the TUI. Previously run_in_background was silently ignored on
|
|
3753
|
+
// resume (this branch returned before the background branch below), so
|
|
3754
|
+
// a resumed agent always blocked the main loop until it finished.
|
|
3755
|
+
const detachedResume = runInBackground || ctx.mode === "tui";
|
|
3756
|
+
if (detachedResume) {
|
|
1950
3757
|
const id = existing.id;
|
|
1951
3758
|
// A detached resume hands control back while the record stays
|
|
1952
3759
|
// "running", so nothing stops the model from resuming the same agent
|
|
@@ -1965,15 +3772,34 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1965
3772
|
if (!record) {
|
|
1966
3773
|
return textResult(`Failed to resume agent "${params.resume}".`);
|
|
1967
3774
|
}
|
|
1968
|
-
const isQueued =
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
`
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
3775
|
+
const isQueued = manager.isQueued(id);
|
|
3776
|
+
const details = { ...detailBaseFor(record), toolUses: record.toolUses, tokens: "", durationMs: 0, status: "background", agentId: id };
|
|
3777
|
+
if (runInBackground) {
|
|
3778
|
+
return textResult(`Agent ${isQueued ? "queued" : "resumed"} in background.\n` +
|
|
3779
|
+
`Agent ID: ${id}\n` +
|
|
3780
|
+
`Type: ${existing.type}\n` +
|
|
3781
|
+
(record.outputFile ? `Output file: ${record.outputFile}\n` : "") +
|
|
3782
|
+
(isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
|
|
3783
|
+
`\nYou will be notified when this agent completes, and that notification carries its complete final report.\n` +
|
|
3784
|
+
`Do not poll for it and do not fabricate its result. Use get_subagent_result only to check status, steer_subagent to send it messages, or stop_subagent to stop it.`, details);
|
|
3785
|
+
}
|
|
3786
|
+
// Interactive foreground resume: startBackgroundResume already passes
|
|
3787
|
+
// `isBackground: true` to the manager, so this returns at once — never
|
|
3788
|
+
// a child promise. Same pending contract as a foreground spawn.
|
|
3789
|
+
return {
|
|
3790
|
+
...textResult(`PENDING — Agent ${isQueued ? "queued" : "resumed"} as a background-managed logical await.\n` +
|
|
3791
|
+
`Agent ID: ${id}\n` +
|
|
3792
|
+
`Type: ${existing.type}\n` +
|
|
3793
|
+
(record.outputFile ? `Output file: ${record.outputFile}\n` : "") +
|
|
3794
|
+
(isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
|
|
3795
|
+
`\nThere is no result yet. The main turn is released and the agent continues in background; ` +
|
|
3796
|
+
`its complete final report will arrive automatically in a later turn — do not poll or wait for it, ` +
|
|
3797
|
+
`and do not fabricate its result.\n` +
|
|
3798
|
+
`Other tools in this batch may carry on without this agent's result — it is not complete yet.`, details),
|
|
3799
|
+
terminate: true,
|
|
3800
|
+
};
|
|
1976
3801
|
}
|
|
3802
|
+
await assertCleanupArtifactAccessAsync(existing);
|
|
1977
3803
|
const record = await manager.resume(params.resume, params.prompt, signal);
|
|
1978
3804
|
if (!record) {
|
|
1979
3805
|
return textResult(`Failed to resume agent "${params.resume}".`);
|
|
@@ -1985,8 +3811,21 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
1985
3811
|
}
|
|
1986
3812
|
return textResult(record.result?.trim() || "No output.", buildDetails(detailBaseFor(record), record));
|
|
1987
3813
|
}
|
|
1988
|
-
//
|
|
1989
|
-
|
|
3814
|
+
// ---- Detached spawn (background call or interactive logical await) ----
|
|
3815
|
+
/**
|
|
3816
|
+
* Spawn this call's agent as a detached, manager-owned run — background
|
|
3817
|
+
* pool slot, no parent-abort wiring, completion notification on settle —
|
|
3818
|
+
* and return as soon as it is registered.
|
|
3819
|
+
*
|
|
3820
|
+
* `startupDeferred` is the interactive half of the contract. A worktree
|
|
3821
|
+
* copy is an awaited git call that can take seconds, and an interactive
|
|
3822
|
+
* call must never hold its receipt open for it, so a TUI call returns
|
|
3823
|
+
* first and observes startup failure through the ordinary completion
|
|
3824
|
+
* channel instead of a throw. Every other path keeps the inline strict
|
|
3825
|
+
* startup error (#179): a returned message would read as a subagent that
|
|
3826
|
+
* ran.
|
|
3827
|
+
*/
|
|
3828
|
+
const spawnDetached = async (startupDeferred) => {
|
|
1990
3829
|
const { state: bgState, callbacks: bgCallbacks } = createActivityTracker(effectiveMaxTurns);
|
|
1991
3830
|
// Wrap onSessionCreated to wire output file streaming.
|
|
1992
3831
|
// The callback lazily reads record.outputFile (set right after spawn)
|
|
@@ -2014,7 +3853,8 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2014
3853
|
isBackground: true,
|
|
2015
3854
|
isolation,
|
|
2016
3855
|
invocation: agentInvocation,
|
|
2017
|
-
|
|
3856
|
+
...(admittedDefinition === undefined ? {} : { agentDefinition: admittedDefinition }),
|
|
3857
|
+
rootSessionId: agentRootSessionId,
|
|
2018
3858
|
...bgCallbacks,
|
|
2019
3859
|
});
|
|
2020
3860
|
// Set output file + join mode synchronously after spawn, before the
|
|
@@ -2026,11 +3866,18 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2026
3866
|
record.toolCallId = toolCallId;
|
|
2027
3867
|
attachTranscript(record, id);
|
|
2028
3868
|
}
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
3869
|
+
if (!startupDeferred) {
|
|
3870
|
+
// Headless callers receive this error inline, not as another wakeup.
|
|
3871
|
+
try {
|
|
3872
|
+
await manager.awaitStartup(id);
|
|
3873
|
+
}
|
|
3874
|
+
catch (error) {
|
|
3875
|
+
if (record)
|
|
3876
|
+
record.resultConsumed = true;
|
|
3877
|
+
cancelNudge(id);
|
|
3878
|
+
throw error;
|
|
3879
|
+
}
|
|
3880
|
+
}
|
|
2034
3881
|
if (joinMode == null || joinMode === 'async') {
|
|
2035
3882
|
// Foreground/no join mode or explicit async — not part of any batch
|
|
2036
3883
|
}
|
|
@@ -2046,8 +3893,6 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2046
3893
|
agentActivity.set(id, bgState);
|
|
2047
3894
|
widget.ensureTimer();
|
|
2048
3895
|
widget.update();
|
|
2049
|
-
fleet.ensureTimer();
|
|
2050
|
-
fleet.update();
|
|
2051
3896
|
// Emit created event
|
|
2052
3897
|
pi.events.emit("subagents:created", {
|
|
2053
3898
|
id,
|
|
@@ -2055,7 +3900,15 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2055
3900
|
description: params.description,
|
|
2056
3901
|
isBackground: true,
|
|
2057
3902
|
});
|
|
2058
|
-
|
|
3903
|
+
return { id, record };
|
|
3904
|
+
};
|
|
3905
|
+
// Background execution
|
|
3906
|
+
if (runInBackground) {
|
|
3907
|
+
// Interactive callers get their receipt before a worktree copy finishes;
|
|
3908
|
+
// headless/print and nested-free programmatic runs keep inline startup
|
|
3909
|
+
// errors because they are not holding a human's turn.
|
|
3910
|
+
const { id, record } = await spawnDetached(ctx.mode === "tui");
|
|
3911
|
+
const isQueued = manager.isQueued(id);
|
|
2059
3912
|
return textResult(`${fallbackNote}Agent ${isQueued ? "queued" : "started"} in background.\n` +
|
|
2060
3913
|
`Agent ID: ${id}\n` +
|
|
2061
3914
|
`Type: ${displayName}\n` +
|
|
@@ -2063,10 +3916,38 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2063
3916
|
(record ? selectionNoteFor(record) : "") +
|
|
2064
3917
|
(record?.outputFile ? `Output file: ${record.outputFile}\n` : "") +
|
|
2065
3918
|
(isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
|
|
2066
|
-
`\nYou will be notified when this agent completes.\n` +
|
|
2067
|
-
`Use get_subagent_result to
|
|
3919
|
+
`\nYou will be notified when this agent completes, and that notification carries its complete final report.\n` +
|
|
3920
|
+
`Do not poll for it and do not fabricate its result. Use get_subagent_result only to check status, steer_subagent to send it messages, or stop_subagent to stop it.\n` +
|
|
2068
3921
|
`Do not duplicate this agent's work.`, { ...detailBaseFor(record), toolUses: 0, tokens: "", durationMs: 0, status: "background", agentId: id });
|
|
2069
3922
|
}
|
|
3923
|
+
// Interactive foreground: a LOGICAL await, not a blocking call.
|
|
3924
|
+
//
|
|
3925
|
+
// The caller asked for a dependency, so it gets one — but in the TUI the
|
|
3926
|
+
// main turn must not sit on a child promise. The agent is background-
|
|
3927
|
+
// managed (pool slot, no parent-abort wiring), the receipt says PENDING,
|
|
3928
|
+
// and `terminate` releases the turn. `terminate` is honored only when
|
|
3929
|
+
// EVERY result in the batch asks for it, so a sibling tool that still
|
|
3930
|
+
// needs its own continuation keeps the turn alive — it must simply treat
|
|
3931
|
+
// this dependency as unfinished. Headless/RPC/print and nested callers
|
|
3932
|
+
// keep the historical inline contract below.
|
|
3933
|
+
if (ctx.mode === "tui") {
|
|
3934
|
+
const { id, record } = await spawnDetached(true);
|
|
3935
|
+
const isQueued = manager.isQueued(id);
|
|
3936
|
+
return {
|
|
3937
|
+
...textResult(`${fallbackNote}PENDING — Agent ${isQueued ? "queued" : "started"} as a background-managed logical await.\n` +
|
|
3938
|
+
`Agent ID: ${id}\n` +
|
|
3939
|
+
`Type: ${displayName}\n` +
|
|
3940
|
+
`Description: ${params.description}\n` +
|
|
3941
|
+
(record ? selectionNoteFor(record) : "") +
|
|
3942
|
+
(record?.outputFile ? `Output file: ${record.outputFile}\n` : "") +
|
|
3943
|
+
(isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
|
|
3944
|
+
`\nThere is no result yet. The main turn is released and the agent continues in background; ` +
|
|
3945
|
+
`its complete final report will arrive automatically in a later turn — do not poll or wait for it, ` +
|
|
3946
|
+
`and do not fabricate its result.\n` +
|
|
3947
|
+
`Other tools in this batch may carry on without this agent's result — it is not complete yet.`, { ...detailBaseFor(record), toolUses: 0, tokens: "", durationMs: 0, status: "background", agentId: id }),
|
|
3948
|
+
terminate: true,
|
|
3949
|
+
};
|
|
3950
|
+
}
|
|
2070
3951
|
// Foreground (synchronous) execution — stream progress via onUpdate
|
|
2071
3952
|
let spinnerFrame = 0;
|
|
2072
3953
|
const startedAt = Date.now();
|
|
@@ -2123,8 +4004,6 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2123
4004
|
fgId = a.id;
|
|
2124
4005
|
agentActivity.set(a.id, fgState);
|
|
2125
4006
|
widget.ensureTimer();
|
|
2126
|
-
fleet.ensureTimer();
|
|
2127
|
-
fleet.update();
|
|
2128
4007
|
break;
|
|
2129
4008
|
}
|
|
2130
4009
|
}
|
|
@@ -2156,8 +4035,9 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2156
4035
|
thinkingLevel: thinking,
|
|
2157
4036
|
isolation,
|
|
2158
4037
|
invocation: agentInvocation,
|
|
4038
|
+
...(admittedDefinition === undefined ? {} : { agentDefinition: admittedDefinition }),
|
|
2159
4039
|
signal,
|
|
2160
|
-
rootSessionId:
|
|
4040
|
+
rootSessionId: agentRootSessionId,
|
|
2161
4041
|
// Deliberately does NOT set fgId: that drives agentActivity, the
|
|
2162
4042
|
// widget and the `finally` cleanup below, none of which should see an
|
|
2163
4043
|
// agent that has no session and may never get one.
|
|
@@ -2179,7 +4059,6 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2179
4059
|
if (fgId) {
|
|
2180
4060
|
agentActivity.delete(fgId);
|
|
2181
4061
|
widget.markFinished(fgId);
|
|
2182
|
-
fleet.onAgentFinished(fgId);
|
|
2183
4062
|
}
|
|
2184
4063
|
}
|
|
2185
4064
|
// Get final token count — from the record, like the cost below it, so the
|
|
@@ -2245,17 +4124,141 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2245
4124
|
*/
|
|
2246
4125
|
const workflowTasks = new Map();
|
|
2247
4126
|
/**
|
|
2248
|
-
*
|
|
4127
|
+
* The ACTUAL detached run, by task id, and the runtime's accepted-journal
|
|
4128
|
+
* drain. Both are registered synchronously before a launcher returns: the
|
|
4129
|
+
* tool and the CLI flag hand control back while the run keeps writing, so
|
|
4130
|
+
* aborting its task is not proof that either has finished. Shutdown awaits
|
|
4131
|
+
* both; see {@link awaitWorkflowQuiescence}.
|
|
2249
4132
|
*
|
|
2250
|
-
*
|
|
2251
|
-
*
|
|
2252
|
-
*
|
|
2253
|
-
*
|
|
4133
|
+
* Deliberately independent of `workflowTasks`: cleanup may forget a deleted
|
|
4134
|
+
* run's pointers, but it cannot disprove that the run is still live, and
|
|
4135
|
+
* dropping its handle would make shutdown return with accepted writes still
|
|
4136
|
+
* in flight. It is cleared by the run settling, not by pointer forgetting.
|
|
2254
4137
|
*/
|
|
4138
|
+
const workflowRunPromises = new Map();
|
|
4139
|
+
const workflowJournalDrains = new Map();
|
|
4140
|
+
/**
|
|
4141
|
+
* Launch a detached workflow run and remember the work it owns.
|
|
4142
|
+
*
|
|
4143
|
+
* `runWorkflowTask` starts the runtime synchronously up to its first await,
|
|
4144
|
+
* so `onJournalDrain` has already registered by the time it returns. The
|
|
4145
|
+
* promise is stored in the same synchronous block, before this function
|
|
4146
|
+
* returns to the tool or the CLI flag.
|
|
4147
|
+
*/
|
|
4148
|
+
function launchWorkflowRun(ctx, task, onSettled) {
|
|
4149
|
+
const run = runWorkflowTask(ctx, task).then(onSettled);
|
|
4150
|
+
workflowRunPromises.set(task.id, run);
|
|
4151
|
+
const forget = () => {
|
|
4152
|
+
if (workflowRunPromises.get(task.id) === run)
|
|
4153
|
+
workflowRunPromises.delete(task.id);
|
|
4154
|
+
// Only now: `finish` drained the accepted writes before the run's own
|
|
4155
|
+
// promise resolved, so the handle cannot be needed again.
|
|
4156
|
+
if (!workflowRunPromises.has(task.id))
|
|
4157
|
+
workflowJournalDrains.delete(task.id);
|
|
4158
|
+
};
|
|
4159
|
+
// Both arms: a throwing notification must not leave the handle behind (or
|
|
4160
|
+
// surface as an unhandled rejection). The run itself never rejects.
|
|
4161
|
+
void run.then(forget, forget);
|
|
4162
|
+
}
|
|
4163
|
+
/** Last admission check after artifact persistence yields; no worker exists yet. */
|
|
4164
|
+
function workflowLaunchRefusal(ctx, epoch, rootSessionId) {
|
|
4165
|
+
if (shuttingDown)
|
|
4166
|
+
return "the session is shutting down";
|
|
4167
|
+
if (sessionEpoch !== epoch || ctx.sessionManager.getSessionId() !== rootSessionId) {
|
|
4168
|
+
return "the session changed while workflow artifacts were persisted";
|
|
4169
|
+
}
|
|
4170
|
+
try {
|
|
4171
|
+
assertCleanupRootAccess(rootSessionId);
|
|
4172
|
+
}
|
|
4173
|
+
catch (error) {
|
|
4174
|
+
return error instanceof Error ? error.message : String(error);
|
|
4175
|
+
}
|
|
4176
|
+
return undefined;
|
|
4177
|
+
}
|
|
4178
|
+
/**
|
|
4179
|
+
* Wait for every detached workflow producer and its accepted journal tail.
|
|
4180
|
+
*
|
|
4181
|
+
* Called after the producers are aborted. Re-reads the handles on every pass
|
|
4182
|
+
* because a launch already in flight can register while the first snapshot is
|
|
4183
|
+
* being awaited; returning on that snapshot would leave that run's accepted
|
|
4184
|
+
* records unwritten. A run promise settles only after the runtime drained its
|
|
4185
|
+
* accepted queue and terminated its worker, and `runWorkflowTask` settles its
|
|
4186
|
+
* final artifact registration before resolving.
|
|
4187
|
+
*/
|
|
4188
|
+
async function awaitWorkflowQuiescence() {
|
|
4189
|
+
for (;;) {
|
|
4190
|
+
const drains = [...workflowJournalDrains.values()];
|
|
4191
|
+
const runs = [...workflowRunPromises.values()];
|
|
4192
|
+
if (drains.length === 0 && runs.length === 0)
|
|
4193
|
+
return;
|
|
4194
|
+
await Promise.allSettled([...drains.map(drain => drain()), ...runs]);
|
|
4195
|
+
}
|
|
4196
|
+
}
|
|
4197
|
+
/**
|
|
4198
|
+
* Deliver the held completion of a workflow that settled during shutdown.
|
|
4199
|
+
*
|
|
4200
|
+
* Called after the run promises and journal tails are awaited, so the notice
|
|
4201
|
+
* already exists in `pendingNudges` and no timer can be left to fire after
|
|
4202
|
+
* the handler returns. Agent notices are not touched: only keys that belong
|
|
4203
|
+
* to a workflow run are delivered here, and an explicitly discarded run is
|
|
4204
|
+
* dropped instead. A throw is swallowed like every other shutdown-time send.
|
|
4205
|
+
*/
|
|
4206
|
+
function flushStoppedWorkflowNudges() {
|
|
4207
|
+
for (const [key, entry] of [...pendingNudges]) {
|
|
4208
|
+
if (!workflowTasks.has(key) && !workflowRunPromises.has(key) && !workflowJournalDrains.has(key))
|
|
4209
|
+
continue;
|
|
4210
|
+
if (discardedWorkflowNotifications.has(key)) {
|
|
4211
|
+
cancelNudge(key);
|
|
4212
|
+
continue;
|
|
4213
|
+
}
|
|
4214
|
+
pendingNudges.delete(key);
|
|
4215
|
+
clearTimeout(entry.timer);
|
|
4216
|
+
try {
|
|
4217
|
+
entry.send();
|
|
4218
|
+
}
|
|
4219
|
+
catch {
|
|
4220
|
+
// A delivery during shutdown must not fail the shutdown itself.
|
|
4221
|
+
}
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
/**
|
|
4225
|
+
* Ownership for cleanup, independent of how many agents the run spawns.
|
|
4226
|
+
* Registration happens at creation and settlement even for a zero-agent
|
|
4227
|
+
* workflow, and the generated paths are the copies THIS run wrote — never a
|
|
4228
|
+
* saved/external source the caller supplied.
|
|
4229
|
+
*/
|
|
4230
|
+
const workflowArtifactPaths = new Map();
|
|
4231
|
+
/** Root a run was created under; settlement must update THAT store. */
|
|
4232
|
+
const workflowArtifactRoots = new Map();
|
|
4233
|
+
const knownGeneratedWorkflowPaths = new Set();
|
|
4234
|
+
function rememberWorkflowArtifacts(id, paths, provenance) {
|
|
4235
|
+
workflowArtifactPaths.set(id, paths);
|
|
4236
|
+
if (provenance.rootSessionId !== undefined)
|
|
4237
|
+
workflowArtifactRoots.set(id, provenance.rootSessionId);
|
|
4238
|
+
workflowArtifactStores.set(id, provenance.store);
|
|
4239
|
+
for (const path of paths.generatedPaths)
|
|
4240
|
+
knownGeneratedWorkflowPaths.add(resolve(path));
|
|
4241
|
+
}
|
|
4242
|
+
async function persistWorkflowArtifactStatus(task) {
|
|
4243
|
+
const paths = workflowArtifactPaths.get(task.id);
|
|
4244
|
+
if (!paths)
|
|
4245
|
+
return undefined;
|
|
4246
|
+
// Pinned at creation: an old run's settlement must never be retargeted to
|
|
4247
|
+
// whatever root happens to be current when its final write is ready.
|
|
4248
|
+
const target = workflowArtifactStores.get(task.id);
|
|
4249
|
+
if (target === undefined)
|
|
4250
|
+
return { saved: false, reason: "workflow-store-missing" };
|
|
4251
|
+
return target.registerWorkflow({
|
|
4252
|
+
id: task.id,
|
|
4253
|
+
generatedPaths: paths.generatedPaths,
|
|
4254
|
+
externalPaths: paths.externalPaths,
|
|
4255
|
+
status: task.status,
|
|
4256
|
+
startedAt: task.startTime,
|
|
4257
|
+
...(task.endTime === undefined ? {} : { completedAt: task.endTime }),
|
|
4258
|
+
});
|
|
4259
|
+
}
|
|
4260
|
+
/** Workflow rows for Agent Hub, using cached counters rather than walking the progress log on render. */
|
|
2255
4261
|
function fleetWorkflows() {
|
|
2256
|
-
// Cached counters only, no derivation: the fleet list calls this on a
|
|
2257
|
-
// 200ms tick and reads the roster several times per update, so walking a
|
|
2258
|
-
// run's progress log here would put O(log) work in the render loop.
|
|
2259
4262
|
return [...workflowTasks.values()].map(task => ({
|
|
2260
4263
|
id: task.id,
|
|
2261
4264
|
name: task.meta?.name ?? task.workflowName ?? task.id,
|
|
@@ -2278,6 +4281,8 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2278
4281
|
const result = await runWorkflow({
|
|
2279
4282
|
script: task.script,
|
|
2280
4283
|
args: task.args,
|
|
4284
|
+
defaultAgentType: task.defaultAgentType,
|
|
4285
|
+
defaultAgentTypeExplicit: task.defaultAgentTypeExplicit,
|
|
2281
4286
|
signal: task.abortController.signal,
|
|
2282
4287
|
host: createWorkflowHost({
|
|
2283
4288
|
pi,
|
|
@@ -2291,6 +4296,10 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2291
4296
|
// The dialog's pause / skip / retry keys run through this; it is dropped
|
|
2292
4297
|
// again when the task settles.
|
|
2293
4298
|
onControl: control => { task.control = control; },
|
|
4299
|
+
// Registered by the runtime before its worker exists. The accepted
|
|
4300
|
+
// records behind a slow append are invisible to the journal module's
|
|
4301
|
+
// own per-path queue, so shutdown and a paused resume need this tail.
|
|
4302
|
+
onJournalDrain: drain => { workflowJournalDrains.set(task.id, drain); },
|
|
2294
4303
|
journal: {
|
|
2295
4304
|
...(task.replay !== undefined ? { entries: task.replay } : {}),
|
|
2296
4305
|
...(task.journalPath !== undefined
|
|
@@ -2303,6 +4312,20 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2303
4312
|
catch (err) {
|
|
2304
4313
|
failWorkflowTask(task, err instanceof Error ? err.message : String(err));
|
|
2305
4314
|
}
|
|
4315
|
+
finally {
|
|
4316
|
+
// Settlement is registered before the result notification, so cleanup
|
|
4317
|
+
// sees a completed/failed run rather than a forever-running one. The
|
|
4318
|
+
// proof added before creation stays active through this final write.
|
|
4319
|
+
try {
|
|
4320
|
+
const persisted = await persistWorkflowArtifactStatus(task);
|
|
4321
|
+
settleWorkflowCleanupProof(task.id, persisted);
|
|
4322
|
+
}
|
|
4323
|
+
catch {
|
|
4324
|
+
const proof = workflowCleanupProofs.get(task.id);
|
|
4325
|
+
if (proof !== undefined)
|
|
4326
|
+
proof.persistenceUncertainty ??= "settlement-registration-threw";
|
|
4327
|
+
}
|
|
4328
|
+
}
|
|
2306
4329
|
}
|
|
2307
4330
|
/**
|
|
2308
4331
|
* Hand a finished run back to the model through the SAME channel a background
|
|
@@ -2311,9 +4334,12 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2311
4334
|
*/
|
|
2312
4335
|
function notifyWorkflowFinished(task) {
|
|
2313
4336
|
widget.update();
|
|
2314
|
-
|
|
4337
|
+
if (discardedWorkflowNotifications.has(task.id))
|
|
4338
|
+
return;
|
|
2315
4339
|
const result = workflowResultText(task);
|
|
2316
4340
|
scheduleNudge(task.id, () => {
|
|
4341
|
+
if (discardedWorkflowNotifications.has(task.id))
|
|
4342
|
+
return;
|
|
2317
4343
|
pi.sendMessage({
|
|
2318
4344
|
customType: "subagent-notification",
|
|
2319
4345
|
content: formatWorkflowNotification(task),
|
|
@@ -2344,6 +4370,7 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2344
4370
|
promptGuidelines: [
|
|
2345
4371
|
"Use SubagentWorkflow when the number of agents depends on something discovered at runtime, when work flows through stages, or when findings should be independently verified. Use Agent for one delegated task or a handful you can name up front.",
|
|
2346
4372
|
"Prefer `pipeline` over `parallel` — a barrier costs wall-clock whenever the stages are unevenly sized.",
|
|
4373
|
+
"Before calling SubagentWorkflow with a scriptPath that depends on a file you just wrote or edited, wait for that Edit/Write call to complete. Never launch the edit and the workflow in the same parallel tool batch — the run can otherwise read the old file.",
|
|
2347
4374
|
"A workflow runs in the background and notifies you when it finishes — do not poll or sleep waiting for it.",
|
|
2348
4375
|
],
|
|
2349
4376
|
parameters: Type.Object({
|
|
@@ -2358,7 +4385,11 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2358
4385
|
description: "Name of a saved workflow — `<name>.js` in .pi/workflows/, .agents/workflows/ or the user's agent dir. Lowest precedence: `scriptPath` and `script` both win over it.",
|
|
2359
4386
|
})),
|
|
2360
4387
|
args: Type.Optional(Type.Any({
|
|
2361
|
-
description: "Exposed to the script as the global `args`, verbatim.
|
|
4388
|
+
description: "Exposed to the script as the global `args`, verbatim. Pass the actual object or array — not a JSON-encoded string, which would reach the script as a string rather than the structure it describes.",
|
|
4389
|
+
})),
|
|
4390
|
+
agentType: Type.Optional(Type.String({
|
|
4391
|
+
minLength: 1,
|
|
4392
|
+
description: 'Default agent type for this run\'s agent() calls that do not name one. Outranks the project\'s workflow default (the "task" role unless configured); a script\'s per-call opts.agentType still outranks this. Resolved from the same registry as the Agent tool.',
|
|
2362
4393
|
})),
|
|
2363
4394
|
resumeFromRunId: Type.Optional(Type.String({
|
|
2364
4395
|
pattern: "^wf_[a-z0-9-]{6,}$",
|
|
@@ -2397,6 +4428,16 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2397
4428
|
}, theme);
|
|
2398
4429
|
},
|
|
2399
4430
|
execute: async (toolCallId, params, _signal, _onUpdate, ctx) => {
|
|
4431
|
+
// Captured before the first await: a session switch or shutdown during a
|
|
4432
|
+
// resumed run's journal wait must be recognisable as a change that
|
|
4433
|
+
// happened AFTER this call was admitted, so no new run is published into
|
|
4434
|
+
// a session that has already moved on.
|
|
4435
|
+
if (shuttingDown)
|
|
4436
|
+
return textResult("Workflow not started: the session is shutting down.");
|
|
4437
|
+
const admitEpoch = sessionEpoch;
|
|
4438
|
+
const requestedAgentType = params.agentType?.trim();
|
|
4439
|
+
if (requestedAgentType === "")
|
|
4440
|
+
return textResult("agentType must be a non-empty agent name.");
|
|
2400
4441
|
const resumeFrom = resolveResumeTarget(params.resumeFromRunId, workflowTasks);
|
|
2401
4442
|
if (resumeFrom !== undefined && !resumeFrom.ok)
|
|
2402
4443
|
return textResult(resumeFrom.message);
|
|
@@ -2409,6 +4450,18 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2409
4450
|
: params, ctx.cwd);
|
|
2410
4451
|
if (!resolved.ok)
|
|
2411
4452
|
return textResult(resolved.message);
|
|
4453
|
+
// Registering generated artifacts requires a bound root; a workflow with
|
|
4454
|
+
// zero agents still owns the script copy and journal it writes below.
|
|
4455
|
+
// Refuse a cleanup-reserved root before binding publishes a lease or runs
|
|
4456
|
+
// maintenance, not only before the generated copy is written.
|
|
4457
|
+
const workflowRootSessionId = ctx.sessionManager.getSessionId();
|
|
4458
|
+
try {
|
|
4459
|
+
assertCleanupRootAccess(workflowRootSessionId);
|
|
4460
|
+
}
|
|
4461
|
+
catch (error) {
|
|
4462
|
+
return textResult(`Workflow not started: ${error instanceof Error ? error.message : String(error)}.`);
|
|
4463
|
+
}
|
|
4464
|
+
await ensureReportBinding(ctx);
|
|
2412
4465
|
// Parsed before anything is scheduled: a bad `meta` is an authoring error
|
|
2413
4466
|
// the model can fix immediately, and reporting it as a background run
|
|
2414
4467
|
// that failed a second later would just cost a turn.
|
|
@@ -2420,10 +4473,61 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2420
4473
|
return textResult(err instanceof Error ? err.message : String(err));
|
|
2421
4474
|
}
|
|
2422
4475
|
const runId = workflowRunId();
|
|
4476
|
+
// Pin root/store before any await or copy. The proof starts before the
|
|
4477
|
+
// generated script copy exists and remains through final registration, so
|
|
4478
|
+
// a zero-agent run is never mistaken for an idle namespace.
|
|
4479
|
+
const workflowStore = (workflowRootSessionId === undefined ? undefined : reportStores.get(workflowRootSessionId)) ?? reportStore;
|
|
4480
|
+
try {
|
|
4481
|
+
assertCleanupRootAccess(workflowRootSessionId);
|
|
4482
|
+
}
|
|
4483
|
+
catch (error) {
|
|
4484
|
+
return textResult(`Workflow not started: ${error instanceof Error ? error.message : String(error)}.`);
|
|
4485
|
+
}
|
|
4486
|
+
// A paused run may still have ACCEPTED journal records behind a slow
|
|
4487
|
+
// append: the runtime serializes them in its own chain, which the journal
|
|
4488
|
+
// module's per-path queue only sees one record at a time. Reading before
|
|
4489
|
+
// that tail settles replays a prefix missing calls the earlier run already
|
|
4490
|
+
// completed, so the resume pays for them again. Wait for the prior run's
|
|
4491
|
+
// accepted queue BEFORE `readJournal`; do not reject paused resumes — the
|
|
4492
|
+
// wait is the fix.
|
|
4493
|
+
if (resumeFrom !== undefined) {
|
|
4494
|
+
const priorDrain = workflowJournalDrains.get(resumeFrom.runId);
|
|
4495
|
+
if (priorDrain !== undefined)
|
|
4496
|
+
await priorDrain();
|
|
4497
|
+
}
|
|
4498
|
+
const replay = resumeFrom !== undefined ? await readJournal(resumeFrom.journalPath) : undefined;
|
|
4499
|
+
// Everything the two waits above protected is re-proved here, in one
|
|
4500
|
+
// synchronous continuation and BEFORE any artifact is written or a new
|
|
4501
|
+
// run is published: the entering session and its epoch (a switch or
|
|
4502
|
+
// shutdown), the root's cleanup reservation, and the resume selection
|
|
4503
|
+
// itself (cleanup can forget the prior run, and the record can move to a
|
|
4504
|
+
// different state while this read was suspended).
|
|
4505
|
+
if (sessionEpoch !== admitEpoch || ctx.sessionManager.getSessionId() !== workflowRootSessionId) {
|
|
4506
|
+
return textResult("Workflow not started: the session changed while the previous run's journal was still being written.");
|
|
4507
|
+
}
|
|
4508
|
+
try {
|
|
4509
|
+
assertCleanupRootAccess(workflowRootSessionId);
|
|
4510
|
+
}
|
|
4511
|
+
catch (error) {
|
|
4512
|
+
return textResult(`Workflow not started: ${error instanceof Error ? error.message : String(error)}.`);
|
|
4513
|
+
}
|
|
4514
|
+
if (resumeFrom !== undefined) {
|
|
4515
|
+
const still = resolveResumeTarget(params.resumeFromRunId, workflowTasks);
|
|
4516
|
+
if (still === undefined || !still.ok) {
|
|
4517
|
+
return textResult(still === undefined
|
|
4518
|
+
? `Workflow not started: resume source "${resumeFrom.runId}" is no longer selected.`
|
|
4519
|
+
: still.message);
|
|
4520
|
+
}
|
|
4521
|
+
if (still.journalPath !== resumeFrom.journalPath) {
|
|
4522
|
+
return textResult(`Workflow not started: the journal for "${resumeFrom.runId}" changed while it was being read.`);
|
|
4523
|
+
}
|
|
4524
|
+
}
|
|
4525
|
+
beginWorkflowCleanupProof(runId, workflowRootSessionId);
|
|
2423
4526
|
// Every invocation lands on disk next to the agent transcripts, so
|
|
2424
4527
|
// iterating is edit-the-file-then-rerun-with-scriptPath rather than
|
|
2425
4528
|
// re-emitting the whole source. The journal sits beside it under the same
|
|
2426
|
-
// id, which is what makes a run id enough to resume from.
|
|
4529
|
+
// id, which is what makes a run id enough to resume from. Written only
|
|
4530
|
+
// after the waits above, so a stale read cannot leave artifacts behind.
|
|
2427
4531
|
let savedPath;
|
|
2428
4532
|
let journalPath;
|
|
2429
4533
|
try {
|
|
@@ -2437,32 +4541,68 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2437
4541
|
journalPath = undefined;
|
|
2438
4542
|
console.warn(`[pi-subagents] could not persist workflow script: ${err instanceof Error ? err.message : String(err)}`);
|
|
2439
4543
|
}
|
|
2440
|
-
|
|
4544
|
+
// A resume re-runs what the earlier run ran, args and default role
|
|
4545
|
+
// included. Only a property the caller actually supplied replaces them:
|
|
4546
|
+
// `Object.hasOwn` rather than `??`, so an explicit `args: null` wins while
|
|
4547
|
+
// an omitted `args` keeps the original (and a new run stays `undefined`,
|
|
4548
|
+
// which scripts already branch on).
|
|
4549
|
+
const args = resumeFrom !== undefined && !Object.hasOwn(params, "args") ? resumeFrom.args : params.args;
|
|
4550
|
+
// Per-run call > the resumed run's frozen choice > the project setting.
|
|
4551
|
+
// A script's `opts.agentType` is applied by the runtime and outranks all.
|
|
4552
|
+
const defaultAgentType = requestedAgentType ?? resumeFrom?.defaultAgentType ?? workflowDefaultAgentType;
|
|
4553
|
+
// Whether something the caller can see named that default: this call's
|
|
4554
|
+
// `agentType`, or the run being resumed. A role reached only through the
|
|
4555
|
+
// project setting is not explicit, which is what keeps an unpinned default
|
|
4556
|
+
// from silently running the parent model (see workflow/host.ts).
|
|
4557
|
+
const defaultAgentTypeExplicit = requestedAgentType !== undefined || (resumeFrom?.defaultAgentTypeExplicit ?? false);
|
|
2441
4558
|
const task = createWorkflowTask({
|
|
2442
4559
|
id: runId,
|
|
2443
4560
|
script: resolved.script,
|
|
2444
4561
|
scriptPath: resolved.scriptPath ?? savedPath,
|
|
2445
|
-
args
|
|
4562
|
+
args,
|
|
4563
|
+
defaultAgentType,
|
|
4564
|
+
defaultAgentTypeExplicit,
|
|
2446
4565
|
meta,
|
|
2447
4566
|
toolCallId,
|
|
2448
4567
|
...(journalPath !== undefined ? { journalPath } : {}),
|
|
2449
4568
|
...(replay !== undefined && replay.length > 0 ? { replay, resumedFrom: resumeFrom.runId } : {}),
|
|
2450
4569
|
});
|
|
4570
|
+
const generatedPaths = [savedPath, journalPath].filter((path) => path !== undefined);
|
|
4571
|
+
const externalPaths = [];
|
|
4572
|
+
if (resolved.scriptPath !== undefined) {
|
|
4573
|
+
const source = resolve(resolved.scriptPath);
|
|
4574
|
+
// A resume may re-run a previous run's generated copy. That copy IS
|
|
4575
|
+
// ours; marking it external would protect it from cleanup forever.
|
|
4576
|
+
if (!knownGeneratedWorkflowPaths.has(source))
|
|
4577
|
+
externalPaths.push(source);
|
|
4578
|
+
}
|
|
4579
|
+
rememberWorkflowArtifacts(runId, { generatedPaths, externalPaths }, {
|
|
4580
|
+
rootSessionId: workflowRootSessionId,
|
|
4581
|
+
store: workflowStore,
|
|
4582
|
+
});
|
|
4583
|
+
updateWorkflowCleanupProof(runId, generatedPaths, externalPaths);
|
|
4584
|
+
const initialPersistence = await persistWorkflowArtifactStatus(task);
|
|
4585
|
+
recordWorkflowPersistenceResult(runId, initialPersistence);
|
|
4586
|
+
// Persistence yields after the earlier session check. This launch may
|
|
4587
|
+
// have missed shutdown's abort sweep; never publish an un-aborted worker.
|
|
4588
|
+
const launchRefusal = workflowLaunchRefusal(ctx, admitEpoch, workflowRootSessionId);
|
|
4589
|
+
if (launchRefusal !== undefined) {
|
|
4590
|
+
task.abortController.abort();
|
|
4591
|
+
settleWorkflowCleanupProof(runId, initialPersistence);
|
|
4592
|
+
return textResult(`Workflow not started: ${launchRefusal}.`);
|
|
4593
|
+
}
|
|
2451
4594
|
workflowTasks.set(runId, task);
|
|
2452
|
-
// The run's own row has to appear now, not when it settles. Its agents
|
|
2453
|
-
// are owned by it, so their lifecycle callbacks no longer refresh these
|
|
2454
|
-
// surfaces — nothing else would register the widget for a run whose
|
|
2455
|
-
// first agent has not started yet.
|
|
2456
4595
|
widget.update();
|
|
2457
|
-
fleet.update();
|
|
2458
4596
|
// Background, like Claude Code: the id comes back now and the run keeps
|
|
2459
|
-
// going without the tool call.
|
|
2460
|
-
|
|
4597
|
+
// going without the tool call. The promise and journal drain are tracked
|
|
4598
|
+
// here, before this returns, so shutdown can await them.
|
|
4599
|
+
launchWorkflowRun(ctx, task, () => notifyWorkflowFinished(task));
|
|
2461
4600
|
return {
|
|
2462
4601
|
content: [{
|
|
2463
4602
|
type: "text",
|
|
2464
4603
|
text: `Workflow "${meta.name}" started in the background.\n` +
|
|
2465
4604
|
`Task ID: ${runId}\n` +
|
|
4605
|
+
`Default agent role: ${task.defaultAgentType}\n` +
|
|
2466
4606
|
(task.scriptPath ? `Script: ${task.scriptPath}\n` : "") +
|
|
2467
4607
|
(task.resumedFrom !== undefined
|
|
2468
4608
|
? `Resuming ${task.resumedFrom}: ${task.replay?.length ?? 0} recorded call(s) available to replay.\n`
|
|
@@ -2530,7 +4670,6 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2530
4670
|
}
|
|
2531
4671
|
workflowsEnabled = false; // not setWorkflowsEnabled: this is not the user pinning it
|
|
2532
4672
|
widget.update();
|
|
2533
|
-
fleet.update();
|
|
2534
4673
|
warn(verdict.message);
|
|
2535
4674
|
if (!verdict.withdraw)
|
|
2536
4675
|
return;
|
|
@@ -2555,9 +4694,10 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2555
4694
|
* session_start for exactly this reason.
|
|
2556
4695
|
*/
|
|
2557
4696
|
let workflowFlagHandled = false;
|
|
2558
|
-
function runWorkflowFlag(ctx) {
|
|
4697
|
+
async function runWorkflowFlag(ctx) {
|
|
2559
4698
|
if (workflowFlagHandled)
|
|
2560
4699
|
return;
|
|
4700
|
+
const admitEpoch = sessionEpoch;
|
|
2561
4701
|
const flag = pi.getFlag(WORKFLOW_FILE_FLAG);
|
|
2562
4702
|
if (flag === undefined || flag === false)
|
|
2563
4703
|
return;
|
|
@@ -2599,14 +4739,45 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2599
4739
|
report(err instanceof Error ? err.message : String(err), "warning");
|
|
2600
4740
|
return;
|
|
2601
4741
|
}
|
|
2602
|
-
const
|
|
4742
|
+
const workflowRootSessionId = ctx.sessionManager.getSessionId();
|
|
4743
|
+
const workflowStore = (workflowRootSessionId === undefined ? undefined : reportStores.get(workflowRootSessionId)) ?? reportStore;
|
|
4744
|
+
const initialRefusal = workflowLaunchRefusal(ctx, admitEpoch, workflowRootSessionId);
|
|
4745
|
+
if (initialRefusal !== undefined) {
|
|
4746
|
+
report(`Workflow not started: ${initialRefusal}.`, "warning");
|
|
4747
|
+
return;
|
|
4748
|
+
}
|
|
4749
|
+
const task = createWorkflowTask({
|
|
4750
|
+
id: workflowRunId(),
|
|
4751
|
+
script,
|
|
4752
|
+
scriptPath: path,
|
|
4753
|
+
meta,
|
|
4754
|
+
defaultAgentType: getWorkflowDefaultAgentType(),
|
|
4755
|
+
});
|
|
4756
|
+
beginWorkflowCleanupProof(task.id, workflowRootSessionId);
|
|
4757
|
+
// A CLI script is user-authored: provenance only, never an owned artifact.
|
|
4758
|
+
rememberWorkflowArtifacts(task.id, { generatedPaths: [], externalPaths: [resolve(path)] }, {
|
|
4759
|
+
rootSessionId: workflowRootSessionId,
|
|
4760
|
+
store: workflowStore,
|
|
4761
|
+
});
|
|
4762
|
+
updateWorkflowCleanupProof(task.id, [], [resolve(path)]);
|
|
4763
|
+
const initialPersistence = await persistWorkflowArtifactStatus(task);
|
|
4764
|
+
recordWorkflowPersistenceResult(task.id, initialPersistence);
|
|
4765
|
+
const launchRefusal = workflowLaunchRefusal(ctx, admitEpoch, workflowRootSessionId);
|
|
4766
|
+
if (launchRefusal !== undefined) {
|
|
4767
|
+
task.abortController.abort();
|
|
4768
|
+
settleWorkflowCleanupProof(task.id, initialPersistence);
|
|
4769
|
+
report(`Workflow not started: ${launchRefusal}.`, "warning");
|
|
4770
|
+
return;
|
|
4771
|
+
}
|
|
2603
4772
|
workflowTasks.set(task.id, task);
|
|
2604
4773
|
widget.update();
|
|
2605
|
-
fleet.update();
|
|
2606
4774
|
report(`Running workflow ${meta.name}…`, "info");
|
|
2607
4775
|
// Detached: session_start is awaited by the host, and a workflow can run for
|
|
2608
|
-
// minutes — blocking here would hold the whole session's startup.
|
|
2609
|
-
|
|
4776
|
+
// minutes — blocking here would hold the whole session's startup. Tracked
|
|
4777
|
+
// before this returns, so shutdown awaits the real run and its journal.
|
|
4778
|
+
launchWorkflowRun(ctx, task, () => {
|
|
4779
|
+
if (discardedWorkflowNotifications.has(task.id))
|
|
4780
|
+
return;
|
|
2610
4781
|
// No tool call to attach a result card to, so the card becomes a session
|
|
2611
4782
|
// entry (same layout), and the outcome is handed to the model as context
|
|
2612
4783
|
// for its next turn rather than forcing one.
|
|
@@ -2617,31 +4788,201 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2617
4788
|
display: false,
|
|
2618
4789
|
}, { deliverAs: "nextTurn" });
|
|
2619
4790
|
widget.update();
|
|
2620
|
-
fleet.update();
|
|
2621
4791
|
});
|
|
2622
4792
|
}
|
|
2623
4793
|
// ---- get_subagent_result tool ----
|
|
4794
|
+
/**
|
|
4795
|
+
* Archived twin of the live result body. Provenance, complete report and an
|
|
4796
|
+
* honest expired/deleted/unknown message; never a notification, never stored
|
|
4797
|
+
* usage billed, and never a fabricated stat for a legacy record.
|
|
4798
|
+
*/
|
|
4799
|
+
async function formatArchivedResult(target, lookup, verbose) {
|
|
4800
|
+
let conversation;
|
|
4801
|
+
if (verbose && lookup.status === "found") {
|
|
4802
|
+
conversation = await target.readConversation(lookup.report);
|
|
4803
|
+
}
|
|
4804
|
+
return formatArchivedReportLookup(lookup, {
|
|
4805
|
+
showCost,
|
|
4806
|
+
...(conversation === undefined ? {} : { conversation }),
|
|
4807
|
+
});
|
|
4808
|
+
}
|
|
2624
4809
|
registerToolReportingUsage(defineTool({
|
|
2625
4810
|
name: SUBAGENT_TOOL_NAMES.GET_RESULT,
|
|
2626
4811
|
label: "Get Agent Result",
|
|
2627
|
-
description: "Check
|
|
4812
|
+
description: "Check a background agent's status or read its result. A finished agent returns its complete final result immediately, and reading it suppresses its completion notification. In the terminal UI, waiting on a running agent releases the main turn instead of blocking: the agent keeps running, nothing has finished yet (treat the receipt as PENDING), and its completion notification later carries the complete final report — do not poll for it. Complete final reports also arrive automatically for agents nobody waited on. Completed reports remain retrievable for 30 days after runtime eviction or reload; exact IDs work across sessions/projects, while handles search the current root session only.",
|
|
2628
4813
|
promptSnippet: "Check status and retrieve results from a background agent",
|
|
4814
|
+
promptGuidelines: [
|
|
4815
|
+
"get_subagent_result with wait: true on a running or queued agent returns at once in the terminal UI: the main turn is released, the agent keeps running, and its completion notification arrives as a later turn carrying the result. Treat that notice as \"pending\" — do not call again to poll, do not fabricate the result, and say the agent is still running if the user asks first.",
|
|
4816
|
+
"When all remaining work is delegated, make wait: true your last/sole tool action to release control without an extra model response. Mixed batches with nonterminating sibling tools continue normally.",
|
|
4817
|
+
"Outside the terminal UI — print mode and nested agents — wait: true blocks until the agent finishes and returns its result inline.",
|
|
4818
|
+
"For completed work evicted from memory or from an earlier session/project, use its exact agent ID. Retained reads return the complete report without another wakeup or rebilling stored usage; verbose opts into existing raw history.",
|
|
4819
|
+
],
|
|
2629
4820
|
parameters: Type.Object({
|
|
2630
4821
|
agent_id: Type.String({
|
|
2631
|
-
description: "The agent ID to check. The agent's handle also works — its `name` if you gave it one, otherwise its type (`explore`, `explore-2`).",
|
|
4822
|
+
description: "The live or retained agent ID to check. Exact IDs work across sessions/projects. The agent's handle also works within the current root session — its `name` if you gave it one, otherwise its type (`explore`, `explore-2`).",
|
|
2632
4823
|
}),
|
|
2633
4824
|
wait: Type.Optional(Type.Boolean({
|
|
2634
|
-
description: "If true, wait for the agent to complete
|
|
4825
|
+
description: "If true, wait for the agent to complete. In the terminal UI a wait on a running agent releases the main turn instead and the completion notification delivers the result; elsewhere it blocks. Default: false.",
|
|
2635
4826
|
})),
|
|
2636
4827
|
verbose: Type.Optional(Type.Boolean({
|
|
2637
|
-
description: "If true, include the agent's
|
|
4828
|
+
description: "If true, include the agent's conversation (messages + tool calls). A released wait honors it in the completion notification as an opt-in transcript excerpt; if that excerpt is bounded, calling this again with verbose: true returns the full conversation. The final report itself is always complete. Default: false.",
|
|
2638
4829
|
})),
|
|
2639
4830
|
}),
|
|
2640
|
-
execute: async (_toolCallId, params, signal, _onUpdate,
|
|
2641
|
-
|
|
2642
|
-
|
|
4831
|
+
execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
|
|
4832
|
+
let record = resolveAgentRef(params.agent_id);
|
|
4833
|
+
// A KNOWN owned live record is refused outright. It must not fall through
|
|
4834
|
+
// to the archive, where a same-id saved row from an earlier run could be
|
|
4835
|
+
// surfaced as if this session's parent could read it.
|
|
4836
|
+
if (record !== undefined && !isTopLevelAgent(record)) {
|
|
2643
4837
|
return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
|
|
2644
4838
|
}
|
|
4839
|
+
if (record !== undefined) {
|
|
4840
|
+
const refusal = cleanupReadRefusal({
|
|
4841
|
+
agentId: record.id,
|
|
4842
|
+
sessionFile: record.sessionFile,
|
|
4843
|
+
rootSessionId: record.rootSessionId,
|
|
4844
|
+
});
|
|
4845
|
+
if (refusal !== undefined) {
|
|
4846
|
+
return textResult(`Agent "${record.id}" is being cleaned up (${refusal}); its report and conversation are not readable right now.`);
|
|
4847
|
+
}
|
|
4848
|
+
}
|
|
4849
|
+
if (record === undefined) {
|
|
4850
|
+
// Runtime eviction/reload miss: durable reports are the only source.
|
|
4851
|
+
// Bind lazily for harnesses that never emitted session_start, and give
|
|
4852
|
+
// the store the current parent's custom records so a pre-upgrade
|
|
4853
|
+
// completion can be recovered authoritatively (never from a raw tail).
|
|
4854
|
+
const root = ctx.sessionManager?.getSessionId?.();
|
|
4855
|
+
const parentEntries = ctx.sessionManager?.getBranch?.() ?? [];
|
|
4856
|
+
// Invalidation token for the entering root, taken BEFORE the lookup: the
|
|
4857
|
+
// whole read below is asynchronous, so a cleanup can begin — and finish —
|
|
4858
|
+
// while it is in flight.
|
|
4859
|
+
const enterToken = cleanupReadTokenFor(root);
|
|
4860
|
+
await ensureReportBinding(ctx);
|
|
4861
|
+
// Read-your-writes, pinned to the entering root/branch: the SDK can
|
|
4862
|
+
// switch its session manager while this filesystem operation yields.
|
|
4863
|
+
const target = (root === undefined ? undefined : reportStores.get(root)) ?? reportStore;
|
|
4864
|
+
const drained = await target.flush();
|
|
4865
|
+
if (drained.status !== "flushed") {
|
|
4866
|
+
return textResult(`Agent "${params.agent_id}" report is not readable yet: pending report writes did not flush (${drained.reason}).`);
|
|
4867
|
+
}
|
|
4868
|
+
const lookup = await target.find(params.agent_id, parentEntries);
|
|
4869
|
+
// The report's own root is what a cleanup would rewrite, and it need not
|
|
4870
|
+
// be the entering one: exact ids are answered across roots.
|
|
4871
|
+
const reportRoot = lookup.status === "found" ? lookup.report.rootSessionId : undefined;
|
|
4872
|
+
const lookupToken = cleanupReadTokenFor(reportRoot);
|
|
4873
|
+
const archivedRefusal = lookup.status === "found"
|
|
4874
|
+
? cleanupReadRefusal({
|
|
4875
|
+
agentId: lookup.report.id,
|
|
4876
|
+
sessionFile: lookup.report.sessionFile,
|
|
4877
|
+
rootSessionId: lookup.report.rootSessionId,
|
|
4878
|
+
})
|
|
4879
|
+
: undefined;
|
|
4880
|
+
if (archivedRefusal !== undefined) {
|
|
4881
|
+
return textResult(`Agent "${params.agent_id}" is being cleaned up (${archivedRefusal}); its archived report is not readable right now.`);
|
|
4882
|
+
}
|
|
4883
|
+
// A resume can start while the archive read is in flight; live always
|
|
4884
|
+
// wins. Recheck again after an opt-in conversation read below.
|
|
4885
|
+
const relive = resolveAgentRef(params.agent_id);
|
|
4886
|
+
if (relive !== undefined) {
|
|
4887
|
+
if (!isTopLevelAgent(relive)) {
|
|
4888
|
+
return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
|
|
4889
|
+
}
|
|
4890
|
+
record = relive;
|
|
4891
|
+
}
|
|
4892
|
+
else {
|
|
4893
|
+
const archived = await formatArchivedResult(target, lookup, params.verbose === true);
|
|
4894
|
+
const postReadRefusal = lookup.status === "found"
|
|
4895
|
+
? cleanupReadRefusal({
|
|
4896
|
+
agentId: lookup.report.id,
|
|
4897
|
+
sessionFile: lookup.report.sessionFile,
|
|
4898
|
+
rootSessionId: lookup.report.rootSessionId,
|
|
4899
|
+
})
|
|
4900
|
+
: undefined;
|
|
4901
|
+
if (postReadRefusal !== undefined) {
|
|
4902
|
+
return textResult(`Agent "${params.agent_id}" is being cleaned up (${postReadRefusal}); its archived report is not readable right now.`);
|
|
4903
|
+
}
|
|
4904
|
+
// The operation's absence proves nothing: a cleanup that ran entirely
|
|
4905
|
+
// inside this read has already released its barriers. Either edge of
|
|
4906
|
+
// that interval moved these tokens, and the durable entry itself is the
|
|
4907
|
+
// final word — after a confirmed deletion it is a receipt, not a body.
|
|
4908
|
+
if (cleanupReadTokenFor(root) !== enterToken || cleanupReadTokenFor(reportRoot) !== lookupToken) {
|
|
4909
|
+
return textResult(`Agent "${params.agent_id}" is no longer available — a cleanup changed its report while it was being read; its body was not returned.`);
|
|
4910
|
+
}
|
|
4911
|
+
if (lookup.status === "found" && lookup.provenance === "archive") {
|
|
4912
|
+
// A deletion receipt is never unlinked, so a durable entry that is
|
|
4913
|
+
// PRESENT and no longer `full` — or rewritten at another generation
|
|
4914
|
+
// — is proof this body was replaced before this continuation
|
|
4915
|
+
// resumed. An UNREADABLE entry proves nothing and is refused: its
|
|
4916
|
+
// absence is not a missing archiver row, it is an unknown one. An
|
|
4917
|
+
// ABSENT entry is refused too: this body's provenance is the
|
|
4918
|
+
// archive row itself, so a proven-missing row means the body this
|
|
4919
|
+
// call captured is no longer the archived report — the token
|
|
4920
|
+
// recheck below cannot make that up. Genuine parent-record and
|
|
4921
|
+
// legacy-output recoveries have their own provenance and do not
|
|
4922
|
+
// reach this branch.
|
|
4923
|
+
const durable = await target.readEntryState(lookup.report.rootSessionId, lookup.report.id);
|
|
4924
|
+
if (durable.status === "uncertain") {
|
|
4925
|
+
return textResult(`Agent "${params.agent_id}" is no longer available — its durable report could not be verified during the read; its body was not returned.`);
|
|
4926
|
+
}
|
|
4927
|
+
if (durable.status === "absent") {
|
|
4928
|
+
return textResult(`Agent "${params.agent_id}" is no longer available — its durable report entry is missing; its body was not returned.`);
|
|
4929
|
+
}
|
|
4930
|
+
if (durable.entry.state !== "full" || durable.entry.entryGeneration !== lookup.entry.entryGeneration) {
|
|
4931
|
+
return textResult(`Agent "${params.agent_id}" is no longer available — its durable report was deleted during the read; its body was not returned.`);
|
|
4932
|
+
}
|
|
4933
|
+
}
|
|
4934
|
+
const afterRead = resolveAgentRef(params.agent_id);
|
|
4935
|
+
if (afterRead === undefined) {
|
|
4936
|
+
// The durable-entry read above is the LAST await. Recheck the
|
|
4937
|
+
// operation's token and this id's availability now, immediately
|
|
4938
|
+
// before the body captured BEFORE that await could be returned.
|
|
4939
|
+
const finalRefusal = lookup.status === "found"
|
|
4940
|
+
? cleanupReadRefusal({
|
|
4941
|
+
agentId: lookup.report.id,
|
|
4942
|
+
sessionFile: lookup.report.sessionFile,
|
|
4943
|
+
rootSessionId: lookup.report.rootSessionId,
|
|
4944
|
+
})
|
|
4945
|
+
: undefined;
|
|
4946
|
+
if (finalRefusal !== undefined) {
|
|
4947
|
+
return textResult(`Agent "${params.agent_id}" is being cleaned up (${finalRefusal}); its archived report is not readable right now.`);
|
|
4948
|
+
}
|
|
4949
|
+
if (cleanupReadTokenFor(root) !== enterToken || cleanupReadTokenFor(reportRoot) !== lookupToken) {
|
|
4950
|
+
return textResult(`Agent "${params.agent_id}" is no longer available — a cleanup changed its report while it was being read; its body was not returned.`);
|
|
4951
|
+
}
|
|
4952
|
+
return textResult(archived);
|
|
4953
|
+
}
|
|
4954
|
+
if (!isTopLevelAgent(afterRead)) {
|
|
4955
|
+
return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
|
|
4956
|
+
}
|
|
4957
|
+
record = afterRead;
|
|
4958
|
+
}
|
|
4959
|
+
}
|
|
4960
|
+
// Interactive wait: release the main turn instead of blocking it.
|
|
4961
|
+
//
|
|
4962
|
+
// Nothing here waits, polls, or arms a second wakeup. The agent's existing
|
|
4963
|
+
// completion notification is the one channel that wakes the parent, and
|
|
4964
|
+
// `terminate` is how this tool result stops pi from making the automatic
|
|
4965
|
+
// post-tool model call — pi honors it only when every finalized result in
|
|
4966
|
+
// the batch asks for it, which is why a sibling that needs its own result
|
|
4967
|
+
// keeps the turn alive rather than being cut off. The result stays
|
|
4968
|
+
// unconsumed, so the notification still fires; that is also what a
|
|
4969
|
+
// cancelled wait leaves behind.
|
|
4970
|
+
if (params.wait && (record.status === "running" || record.status === "queued") && ctx.mode === "tui") {
|
|
4971
|
+
// Same contract as the blocking path's `abortable`: an already-cancelled
|
|
4972
|
+
// call rejects, and nothing is registered for a caller that is gone.
|
|
4973
|
+
if (signal?.aborted)
|
|
4974
|
+
throw signal.reason;
|
|
4975
|
+
deferResultDelivery(record, { verbose: params.verbose === true });
|
|
4976
|
+
return {
|
|
4977
|
+
...textResult(`PENDING — Agent ${record.id} is still ${record.status}; nothing has finished and there is no result yet. The main turn yielded.\n` +
|
|
4978
|
+
`The agent continues in the background. Its complete final report will arrive automatically in a later turn` +
|
|
4979
|
+
(params.verbose
|
|
4980
|
+
? ", with the full conversation appended as an opt-in transcript excerpt — the report itself is never truncated, and get_subagent_result with verbose: true returns the full transcript.\n"
|
|
4981
|
+
: ".\n") +
|
|
4982
|
+
`Treat it as PENDING: do not poll or wait again, and do not fabricate its result.`),
|
|
4983
|
+
terminate: true,
|
|
4984
|
+
};
|
|
4985
|
+
}
|
|
2645
4986
|
// Wait for completion if requested. Cancellation stops only this tool
|
|
2646
4987
|
// call; the background agent keeps running and remains unconsumed so its
|
|
2647
4988
|
// completion notification can still be delivered.
|
|
@@ -2688,10 +5029,13 @@ Terse command-style prompts produce shallow, generic work.
|
|
|
2688
5029
|
|
|
2689
5030
|
Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? "" : "s"} arrived after the agent finished and ${record.droppedSteers === 1 ? "was" : "were"} discarded.`;
|
|
2690
5031
|
}
|
|
2691
|
-
// Mark result as consumed — suppresses the completion notification
|
|
5032
|
+
// Mark result as consumed — suppresses the completion notification, and
|
|
5033
|
+
// spends any deferred interest: the parent has the result already, so the
|
|
5034
|
+
// wakeup it asked for has nothing left to deliver.
|
|
2692
5035
|
if (record.status !== "running" && record.status !== "queued") {
|
|
2693
5036
|
record.resultConsumed = true;
|
|
2694
|
-
cancelNudge(
|
|
5037
|
+
cancelNudge(record.id);
|
|
5038
|
+
deferredResultInterest.delete(record.id);
|
|
2695
5039
|
}
|
|
2696
5040
|
// Verbose: include full conversation
|
|
2697
5041
|
if (params.verbose && record.session) {
|
|
@@ -2717,8 +5061,28 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
2717
5061
|
message: Type.String({
|
|
2718
5062
|
description: "The steering message to send. This will appear as a user message in the agent's conversation.",
|
|
2719
5063
|
}),
|
|
5064
|
+
goalGuard: Type.Optional(Type.Object({
|
|
5065
|
+
version: Type.Literal(1),
|
|
5066
|
+
sessionId: Type.String({ description: "Live root session id the guard was issued for" }),
|
|
5067
|
+
goalId: Type.String({ description: "Goal that owns this guarded steering action" }),
|
|
5068
|
+
runGeneration: Type.Number({ description: "Exact run generation of the target agent in the goal agent snapshot" }),
|
|
5069
|
+
operationId: Type.String({ description: "Unique action id; a repeat for the same run generation is refused" }),
|
|
5070
|
+
}, {
|
|
5071
|
+
description: "Reserved for goal-orchestration clients. Ordinary steering must omit it; an unguarded call behaves exactly as before and a malformed or unavailable guard is refused without steering.",
|
|
5072
|
+
})),
|
|
2720
5073
|
}),
|
|
2721
|
-
execute: async (_toolCallId, params,
|
|
5074
|
+
execute: async (_toolCallId, params, signal, _onUpdate, _ctx) => {
|
|
5075
|
+
if (params.goalGuard !== undefined) {
|
|
5076
|
+
// Same ORIGINAL tool, same permission hooks. The bridge validates
|
|
5077
|
+
// session/ownership/generation/cancellation and delivers through
|
|
5078
|
+
// steerAcknowledged; a refusal throws a real tool error.
|
|
5079
|
+
const receipt = await goalBridge.steer(params.goalGuard, params.agent_id, params.message, signal);
|
|
5080
|
+
pi.events.emit("subagents:steered", { id: receipt.agentId, message: params.message });
|
|
5081
|
+
return textResult(`Steering message sent to agent ${receipt.agentId} (run ${receipt.runGeneration}). ` +
|
|
5082
|
+
(receipt.abortedAfterDelivery
|
|
5083
|
+
? "It was acknowledged before the caller's cancellation and cannot be unsent."
|
|
5084
|
+
: "The agent will process it after its current tool execution."));
|
|
5085
|
+
}
|
|
2722
5086
|
const record = resolveAgentRef(params.agent_id);
|
|
2723
5087
|
if (!record || !isTopLevelAgent(record)) {
|
|
2724
5088
|
return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
|
|
@@ -2774,19 +5138,13 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
2774
5138
|
}));
|
|
2775
5139
|
// ---- main-session awareness of live agents ----
|
|
2776
5140
|
// Top-level only by construction: this extension returns early in child
|
|
2777
|
-
// sessions (see the top of this function).
|
|
2778
|
-
//
|
|
2779
|
-
//
|
|
2780
|
-
pi.on("before_agent_start", (
|
|
2781
|
-
const
|
|
2782
|
-
if (
|
|
2783
|
-
return;
|
|
2784
|
-
const sections = options.sections;
|
|
2785
|
-
if (typeof sections !== "object" || sections === null)
|
|
2786
|
-
return;
|
|
2787
|
-
const text = buildActiveAgentsSection(manager.listAgents().filter(isTopLevelAgent));
|
|
2788
|
-
if (text)
|
|
2789
|
-
sections[ACTIVE_AGENTS_SECTION] = text;
|
|
5141
|
+
// sessions (see the top of this function). An appended hidden message, not a
|
|
5142
|
+
// `systemPromptOptions` section: see active-agents-prompt.ts for why a section
|
|
5143
|
+
// edit costs the prompt cache. Never a full systemPrompt either.
|
|
5144
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
5145
|
+
const content = nextActiveAgentsMessage(manager.listAgents().filter(isTopLevelAgent), ctx.sessionManager?.getBranch?.() ?? []);
|
|
5146
|
+
if (content)
|
|
5147
|
+
return { message: { customType: ACTIVE_AGENTS_MESSAGE_TYPE, content, display: false } };
|
|
2790
5148
|
});
|
|
2791
5149
|
// ---- stop_subagent tool ----
|
|
2792
5150
|
registerToolReportingUsage(defineTool({
|
|
@@ -2808,7 +5166,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
2808
5166
|
if (record.status !== "running" && record.status !== "queued") {
|
|
2809
5167
|
return textResult(`Agent ${record.id} is already ${record.status}; nothing to stop.`);
|
|
2810
5168
|
}
|
|
2811
|
-
const wasQueued = record.
|
|
5169
|
+
const wasQueued = manager.isQueued(record.id);
|
|
2812
5170
|
if (!manager.abort(record.id)) {
|
|
2813
5171
|
return textResult(`Agent ${record.id} is already ${record.status}; nothing to stop.`);
|
|
2814
5172
|
}
|
|
@@ -2847,7 +5205,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
2847
5205
|
return `${label} (→ ${resolvedFull.replace(/-\d{8}$/, "")})`;
|
|
2848
5206
|
}
|
|
2849
5207
|
async function showAgentsMenu(ctx) {
|
|
2850
|
-
|
|
5208
|
+
await reloadCustomAgentsAsync();
|
|
2851
5209
|
const allNames = getAllTypes();
|
|
2852
5210
|
// Build select options
|
|
2853
5211
|
const options = [];
|
|
@@ -2982,25 +5340,87 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
2982
5340
|
* caller — geometry and dismissal mirror the viewer wiring exactly.
|
|
2983
5341
|
*/
|
|
2984
5342
|
async function showFleetOverlay(ctx) {
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
5343
|
+
// The fleet frame is anchored over the whole terminal, including the
|
|
5344
|
+
// editor container that `ctx.ui.input` draws its prompt into. Hide it while
|
|
5345
|
+
// a prompt is open (so the question and the typed answer are visible) and
|
|
5346
|
+
// restore it once the prompt resolves, cancellation and errors included.
|
|
5347
|
+
hubOpen = true;
|
|
5348
|
+
let overlay;
|
|
5349
|
+
let closed = false;
|
|
5350
|
+
const promptWhileHidden = async (title) => {
|
|
5351
|
+
const handle = overlay;
|
|
5352
|
+
if (!handle || closed)
|
|
5353
|
+
return ctx.ui.input(title, "");
|
|
5354
|
+
handle.setHidden(true);
|
|
5355
|
+
try {
|
|
5356
|
+
return await ctx.ui.input(title, "");
|
|
5357
|
+
}
|
|
5358
|
+
finally {
|
|
5359
|
+
// The overlay may have been torn down while the prompt was open; only
|
|
5360
|
+
// touch it when it is still the live surface.
|
|
5361
|
+
if (!closed)
|
|
5362
|
+
handle.setHidden(false);
|
|
5363
|
+
}
|
|
5364
|
+
};
|
|
5365
|
+
try {
|
|
5366
|
+
await ctx.ui.custom((tui, theme, _keybindings, done) => new FleetOverlay({
|
|
5367
|
+
tui,
|
|
5368
|
+
theme,
|
|
5369
|
+
records: () => manager.listAgents().filter(isTopLevelAgent),
|
|
5370
|
+
// No workflow source when the feature is off, exactly as the
|
|
5371
|
+
// conversation surfaces treat it: never advertise a switched-off run.
|
|
5372
|
+
workflows: isWorkflowsEnabled() ? fleetWorkflows : () => [],
|
|
5373
|
+
activity: agentActivity,
|
|
5374
|
+
showCost: isShowCostEnabled,
|
|
5375
|
+
openAgent: record => viewAgentConversation(ctx, record),
|
|
5376
|
+
openWorkflow: id => openWorkflowFromFleet(id, workflowMenuDeps),
|
|
5377
|
+
notify: (message, type) => ctx.ui.notify(message, type),
|
|
5378
|
+
done: result => {
|
|
5379
|
+
closed = true;
|
|
5380
|
+
done(result);
|
|
5381
|
+
},
|
|
5382
|
+
// Tree view: nested children too, never workflow-owned agents (the run reports for them).
|
|
5383
|
+
allRecords: () => manager.listAgents().filter(record => !record.workflowId),
|
|
5384
|
+
stopAgent: record => manager.abort(record.id),
|
|
5385
|
+
resumeAgent: async (record) => {
|
|
5386
|
+
if (!record.session) {
|
|
5387
|
+
ctx.ui.notify("Agent session is gone — it cannot be resumed.", "warning");
|
|
5388
|
+
return;
|
|
5389
|
+
}
|
|
5390
|
+
const message = await promptWhileHidden(`Resume ${record.alias ?? record.handle ?? record.type} with:`);
|
|
5391
|
+
if (!message?.trim())
|
|
5392
|
+
return;
|
|
5393
|
+
const registry = await reloadCustomAgentsAsync();
|
|
5394
|
+
const config = getAgentConfigIn(registry, record.type);
|
|
5395
|
+
const resumed = await startBackgroundResume(ctx, record, message.trim(), {
|
|
5396
|
+
outputTranscript: config?.outputTranscript ?? getOutputTranscriptDefault(),
|
|
5397
|
+
maxTurns: normalizeMaxTurns(config?.maxTurns ?? getDefaultMaxTurns()),
|
|
5398
|
+
});
|
|
5399
|
+
ctx.ui.notify(resumed ? `Resuming "${record.description}".` : "Could not resume — it is still running.", resumed ? "info" : "warning");
|
|
5400
|
+
},
|
|
5401
|
+
}), {
|
|
5402
|
+
overlay: true,
|
|
5403
|
+
overlayOptions: { anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 },
|
|
5404
|
+
onHandle: handle => {
|
|
5405
|
+
overlay = handle;
|
|
5406
|
+
},
|
|
5407
|
+
});
|
|
5408
|
+
}
|
|
5409
|
+
finally {
|
|
5410
|
+
closed = true;
|
|
5411
|
+
hubOpen = false;
|
|
5412
|
+
}
|
|
3002
5413
|
}
|
|
3003
5414
|
async function viewAgentConversation(ctx, record, onCloseReady) {
|
|
5415
|
+
const cleanupRefusal = cleanupReadRefusal({
|
|
5416
|
+
agentId: record.id,
|
|
5417
|
+
sessionFile: record.sessionFile,
|
|
5418
|
+
rootSessionId: record.rootSessionId,
|
|
5419
|
+
});
|
|
5420
|
+
if (cleanupRefusal !== undefined) {
|
|
5421
|
+
ctx.ui.notify(`"${record.description}" is being cleaned up (${cleanupRefusal}); its conversation is not readable right now.`, "warning");
|
|
5422
|
+
return;
|
|
5423
|
+
}
|
|
3004
5424
|
if (!record.session) {
|
|
3005
5425
|
ctx.ui.notify(`Agent is ${record.status === "queued" ? "queued" : "expired"} — no session available.`, "info");
|
|
3006
5426
|
return;
|
|
@@ -3023,7 +5443,8 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
3023
5443
|
}
|
|
3024
5444
|
return accepted;
|
|
3025
5445
|
}
|
|
3026
|
-
const
|
|
5446
|
+
const registry = await reloadCustomAgentsAsync();
|
|
5447
|
+
const config = getAgentConfigIn(registry, record.type);
|
|
3027
5448
|
return !!await startBackgroundResume(ctx, record, message, {
|
|
3028
5449
|
outputTranscript: config?.outputTranscript ?? getOutputTranscriptDefault(),
|
|
3029
5450
|
maxTurns: normalizeMaxTurns(config?.maxTurns ?? getDefaultMaxTurns()),
|
|
@@ -3073,7 +5494,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
3073
5494
|
if (edited !== undefined && edited !== content) {
|
|
3074
5495
|
const { writeFileSync } = await import("node:fs");
|
|
3075
5496
|
writeFileSync(file.path, edited, "utf-8");
|
|
3076
|
-
|
|
5497
|
+
await reloadCustomAgentsAsync();
|
|
3077
5498
|
ctx.ui.notify(`Updated ${file.path}`, "info");
|
|
3078
5499
|
}
|
|
3079
5500
|
}
|
|
@@ -3082,7 +5503,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
3082
5503
|
const confirmed = await ctx.ui.confirm("Delete agent", `Delete ${name} from ${file.location} (${file.path})?`);
|
|
3083
5504
|
if (confirmed) {
|
|
3084
5505
|
unlinkSync(file.path);
|
|
3085
|
-
|
|
5506
|
+
await reloadCustomAgentsAsync();
|
|
3086
5507
|
ctx.ui.notify(`Deleted ${file.path}`, "info");
|
|
3087
5508
|
}
|
|
3088
5509
|
}
|
|
@@ -3091,7 +5512,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
3091
5512
|
const confirmed = await ctx.ui.confirm("Reset to default", `Delete override ${file.path} and restore embedded default?`);
|
|
3092
5513
|
if (confirmed) {
|
|
3093
5514
|
unlinkSync(file.path);
|
|
3094
|
-
|
|
5515
|
+
await reloadCustomAgentsAsync();
|
|
3095
5516
|
ctx.ui.notify(`Restored default ${name}`, "info");
|
|
3096
5517
|
}
|
|
3097
5518
|
}
|
|
@@ -3124,7 +5545,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
3124
5545
|
const content = serializeAgentFile(cfg);
|
|
3125
5546
|
const { writeFileSync } = await import("node:fs");
|
|
3126
5547
|
writeFileSync(targetPath, content, "utf-8");
|
|
3127
|
-
|
|
5548
|
+
await reloadCustomAgentsAsync();
|
|
3128
5549
|
ctx.ui.notify(`Ejected ${name} to ${targetPath}`, "info");
|
|
3129
5550
|
}
|
|
3130
5551
|
/** Disable an agent: set enabled: false in its .md file, or create a stub for built-in defaults. */
|
|
@@ -3146,7 +5567,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
3146
5567
|
}
|
|
3147
5568
|
const { writeFileSync } = await import("node:fs");
|
|
3148
5569
|
writeFileSync(file.path, updated, "utf-8");
|
|
3149
|
-
|
|
5570
|
+
await reloadCustomAgentsAsync();
|
|
3150
5571
|
ctx.ui.notify(`Disabled ${name} (${file.path})`, "info");
|
|
3151
5572
|
return;
|
|
3152
5573
|
}
|
|
@@ -3162,7 +5583,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
3162
5583
|
const targetPath = join(targetDir, `${name}.md`);
|
|
3163
5584
|
const { writeFileSync } = await import("node:fs");
|
|
3164
5585
|
writeFileSync(targetPath, "---\nenabled: false\n---\n", "utf-8");
|
|
3165
|
-
|
|
5586
|
+
await reloadCustomAgentsAsync();
|
|
3166
5587
|
ctx.ui.notify(`Disabled ${name} (${targetPath})`, "info");
|
|
3167
5588
|
}
|
|
3168
5589
|
/** Enable a disabled agent by removing enabled: false from its frontmatter. */
|
|
@@ -3182,12 +5603,12 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
|
|
|
3182
5603
|
// If the file was just a stub ("---\n---\n"), delete it to restore the built-in default
|
|
3183
5604
|
if (isEmptyStub(updated)) {
|
|
3184
5605
|
unlinkSync(file.path);
|
|
3185
|
-
|
|
5606
|
+
await reloadCustomAgentsAsync();
|
|
3186
5607
|
ctx.ui.notify(`Enabled ${name} (removed ${file.path})`, "info");
|
|
3187
5608
|
}
|
|
3188
5609
|
else {
|
|
3189
5610
|
writeFileSync(file.path, updated, "utf-8");
|
|
3190
|
-
|
|
5611
|
+
await reloadCustomAgentsAsync();
|
|
3191
5612
|
ctx.ui.notify(`Enabled ${name} (${file.path})`, "info");
|
|
3192
5613
|
}
|
|
3193
5614
|
}
|
|
@@ -3275,7 +5696,8 @@ Guidelines for choosing settings:
|
|
|
3275
5696
|
Write the file using the write tool. Only write the file, nothing else.`;
|
|
3276
5697
|
const { record } = await manager.spawnAndWait(pi, ctx, "general-purpose", generatePrompt, {
|
|
3277
5698
|
description: `Generate ${name} agent`,
|
|
3278
|
-
|
|
5699
|
+
// No hardcoded turn cap here: the configured agent/default budget (or
|
|
5700
|
+
// unlimited) decides, so a wizard run is not silently cut at five turns.
|
|
3279
5701
|
// Exempt from maxConcurrentForeground. This runs from a modal wizard, not
|
|
3280
5702
|
// a tool call: it passes no signal, and Esc in `ctx.ui` never reaches the
|
|
3281
5703
|
// manager — so a user waiting behind a full pool would have no way to
|
|
@@ -3287,7 +5709,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3287
5709
|
ctx.ui.notify(`Generation failed: ${record.error}`, "warning");
|
|
3288
5710
|
return;
|
|
3289
5711
|
}
|
|
3290
|
-
|
|
5712
|
+
await reloadCustomAgentsAsync();
|
|
3291
5713
|
if (existsSync(targetPath)) {
|
|
3292
5714
|
ctx.ui.notify(`Created ${targetPath}`, "info");
|
|
3293
5715
|
}
|
|
@@ -3369,7 +5791,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3369
5791
|
}
|
|
3370
5792
|
const { writeFileSync } = await import("node:fs");
|
|
3371
5793
|
writeFileSync(targetPath, content, "utf-8");
|
|
3372
|
-
|
|
5794
|
+
await reloadCustomAgentsAsync();
|
|
3373
5795
|
ctx.ui.notify(`Created ${targetPath}`, "info");
|
|
3374
5796
|
}
|
|
3375
5797
|
/**
|
|
@@ -3390,6 +5812,9 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3390
5812
|
// normalizeMaxTurns() in agent-runner.ts (which maps 0 → undefined).
|
|
3391
5813
|
defaultMaxTurns: getDefaultMaxTurns() ?? 0,
|
|
3392
5814
|
graceTurns: getGraceTurns(),
|
|
5815
|
+
// The policy the tool schema and resolver actually honor, written back so
|
|
5816
|
+
// an unrelated settings save cannot erase it.
|
|
5817
|
+
allowPerCallTurnLimits: getAllowPerCallTurnLimits(),
|
|
3393
5818
|
defaultJoinMode: getDefaultJoinMode(),
|
|
3394
5819
|
backgroundByDefault: getBackgroundByDefault(),
|
|
3395
5820
|
schedulingEnabled: isSchedulingEnabled(),
|
|
@@ -3397,10 +5822,10 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3397
5822
|
strictAgentFiles,
|
|
3398
5823
|
disableDefaultAgents: isDefaultsDisabled(),
|
|
3399
5824
|
toolDescriptionMode: getToolDescriptionMode(),
|
|
3400
|
-
fleetView: isFleetViewEnabled(),
|
|
3401
5825
|
agentMentions: getAgentMentionMode(),
|
|
3402
5826
|
rememberAgents: getRememberAgents(),
|
|
3403
5827
|
widgetMode: getWidgetMode(),
|
|
5828
|
+
widgetPlacement: getWidgetPlacement(),
|
|
3404
5829
|
outputTranscript: getOutputTranscriptDefault(),
|
|
3405
5830
|
worktreeIsolation: isWorktreeIsolationEnabled(),
|
|
3406
5831
|
// The user's answer, not the effective one. A stand-down for another
|
|
@@ -3411,6 +5836,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3411
5836
|
// JSON.stringify, so unset stays unset — same reasoning as
|
|
3412
5837
|
// `fallbackSubagent` below.
|
|
3413
5838
|
workflowsEnabled: isWorkflowsPinned() ? isWorkflowsEnabled() : undefined,
|
|
5839
|
+
workflowDefaultAgentType: getWorkflowDefaultAgentType(),
|
|
3414
5840
|
maxSubagentDepth: getMaxSubagentDepth(),
|
|
3415
5841
|
// Keep unset strict dispatch unset; don't turn it into an explicit
|
|
3416
5842
|
// fallback when saving an unrelated setting. JSON.stringify drops undefined.
|
|
@@ -3437,6 +5863,15 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3437
5863
|
// fallback targets are offered; unrelated saves preserve unset.
|
|
3438
5864
|
const fallbackValue = getFallbackSubagent() ?? NO_FALLBACK;
|
|
3439
5865
|
const fallbackValues = [...new Set([...getAvailableTypes(), NO_FALLBACK])];
|
|
5866
|
+
// The role list offers enabled agents only, but never drops a configured
|
|
5867
|
+
// default that is currently disabled or renamed: that would make the
|
|
5868
|
+
// stored value unrepresentable in the list and invite a stray save to
|
|
5869
|
+
// replace it with whatever happens to be available.
|
|
5870
|
+
const workflowDefault = getWorkflowDefaultAgentType();
|
|
5871
|
+
const availableRoles = getAvailableTypes();
|
|
5872
|
+
const workflowDefaultValues = availableRoles.includes(workflowDefault)
|
|
5873
|
+
? availableRoles
|
|
5874
|
+
: [workflowDefault, ...availableRoles];
|
|
3440
5875
|
return [
|
|
3441
5876
|
{
|
|
3442
5877
|
id: "maxConcurrent",
|
|
@@ -3448,7 +5883,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3448
5883
|
{
|
|
3449
5884
|
id: "maxConcurrentForeground",
|
|
3450
5885
|
label: "Max foreground concurrency",
|
|
3451
|
-
description: "Max concurrent foreground
|
|
5886
|
+
description: "Max concurrent inline foreground agents — headless/print/RPC only; terminal-UI foreground requests yield as logical awaits (0 = unlimited, Enter to type)",
|
|
3452
5887
|
currentValue: String(mcf),
|
|
3453
5888
|
values: [String(mcf)],
|
|
3454
5889
|
},
|
|
@@ -3459,6 +5894,13 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3459
5894
|
currentValue: String(dmt),
|
|
3460
5895
|
values: [String(dmt)],
|
|
3461
5896
|
},
|
|
5897
|
+
{
|
|
5898
|
+
id: "allowPerCallTurnLimits",
|
|
5899
|
+
label: "Allow per-call turn limits",
|
|
5900
|
+
description: "Let an Agent/nested/RPC caller's max_turns cap a run (off = configured agent/role and default budgets decide; the parameter is hidden from the tool schema on next pi session)",
|
|
5901
|
+
currentValue: getAllowPerCallTurnLimits() ? "on" : "off",
|
|
5902
|
+
values: ["on", "off"],
|
|
5903
|
+
},
|
|
3462
5904
|
{
|
|
3463
5905
|
id: "graceTurns",
|
|
3464
5906
|
label: "Grace turns",
|
|
@@ -3483,7 +5925,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3483
5925
|
{
|
|
3484
5926
|
id: "backgroundByDefault",
|
|
3485
5927
|
label: "Background by default",
|
|
3486
|
-
description: "An Agent call that doesn't say runs detached (off =
|
|
5928
|
+
description: "An Agent call that doesn't say runs detached (off = interactive requests yield immediately as a PENDING logical await with the report arriving later; headless/print/RPC calls block and return inline)",
|
|
3487
5929
|
currentValue: getBackgroundByDefault() ? "on" : "off",
|
|
3488
5930
|
values: ["on", "off"],
|
|
3489
5931
|
},
|
|
@@ -3502,6 +5944,13 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3502
5944
|
currentValue: isWorkflowsEnabled() ? "on" : "off",
|
|
3503
5945
|
values: ["on", "off"],
|
|
3504
5946
|
},
|
|
5947
|
+
{
|
|
5948
|
+
id: "workflowDefaultAgentType",
|
|
5949
|
+
label: "Workflow default agent",
|
|
5950
|
+
description: "Agent type a workflow's agent() calls use when they name none (default: task). A SubagentWorkflow call's agentType, or a script's per-call opts.agentType, outranks it. Applies to runs started from now on; a stored value is kept even while that role is unavailable.",
|
|
5951
|
+
currentValue: workflowDefault,
|
|
5952
|
+
values: workflowDefaultValues,
|
|
5953
|
+
},
|
|
3505
5954
|
{
|
|
3506
5955
|
id: "scopeModels",
|
|
3507
5956
|
label: "Scope models",
|
|
@@ -3554,7 +6003,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3554
6003
|
{
|
|
3555
6004
|
id: "showCost",
|
|
3556
6005
|
label: "Show cost",
|
|
3557
|
-
description: "Show an estimated `~$0.0042` beside subagent token counts in the widget,
|
|
6006
|
+
description: "Show an estimated `~$0.0042` beside subagent token counts in the widget, Agent Hub, results and notifications. Priced by pi from the model's rates — omitted entirely for a model it has no rates for.",
|
|
3558
6007
|
currentValue: isShowCostEnabled() ? "on" : "off",
|
|
3559
6008
|
values: ["on", "off"],
|
|
3560
6009
|
},
|
|
@@ -3572,13 +6021,6 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3572
6021
|
currentValue: getViewerMarkdown(),
|
|
3573
6022
|
values: ["off", "assistant", "all"],
|
|
3574
6023
|
},
|
|
3575
|
-
{
|
|
3576
|
-
id: "fleetView",
|
|
3577
|
-
label: "Fleet view",
|
|
3578
|
-
description: "Claude Code-style main+subagents list below the editor (↓/← to navigate, Enter to view)",
|
|
3579
|
-
currentValue: isFleetViewEnabled() ? "on" : "off",
|
|
3580
|
-
values: ["on", "off"],
|
|
3581
|
-
},
|
|
3582
6024
|
{
|
|
3583
6025
|
id: "agentMentions",
|
|
3584
6026
|
label: "Agent mentions",
|
|
@@ -3596,10 +6038,17 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3596
6038
|
{
|
|
3597
6039
|
id: "widgetMode",
|
|
3598
6040
|
label: "Widget",
|
|
3599
|
-
description: "
|
|
6041
|
+
description: "Compact agent widget: all = every agent; background = hide foreground (they already render inline); off = hide the widget.",
|
|
3600
6042
|
currentValue: getWidgetMode(),
|
|
3601
6043
|
values: ["all", "background", "off"],
|
|
3602
6044
|
},
|
|
6045
|
+
{
|
|
6046
|
+
id: "widgetPlacement",
|
|
6047
|
+
label: "Widget placement",
|
|
6048
|
+
description: "Place the compact agent list above or below the editor. Applied immediately; above is the default.",
|
|
6049
|
+
currentValue: getWidgetPlacement(),
|
|
6050
|
+
values: ["above", "below"],
|
|
6051
|
+
},
|
|
3603
6052
|
{
|
|
3604
6053
|
id: "toolDescriptionMode",
|
|
3605
6054
|
label: "Tool description",
|
|
@@ -3638,6 +6087,20 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3638
6087
|
notifyApplied(ctx, `Default max turns set to ${n}`);
|
|
3639
6088
|
}
|
|
3640
6089
|
}
|
|
6090
|
+
else if (id === "allowPerCallTurnLimits") {
|
|
6091
|
+
const enabled = value === "on";
|
|
6092
|
+
if (enabled === getAllowPerCallTurnLimits()) {
|
|
6093
|
+
ctx.ui.notify(`Per-call turn limits already ${enabled ? "allowed" : "ignored"}.`, "info");
|
|
6094
|
+
}
|
|
6095
|
+
else {
|
|
6096
|
+
setAllowPerCallTurnLimits(enabled);
|
|
6097
|
+
// Runtime filtering is live; the `max_turns` parameter only appears or
|
|
6098
|
+
// disappears from the tool schema when the schema is built at load.
|
|
6099
|
+
notifyApplied(ctx, enabled
|
|
6100
|
+
? "Per-call turn limits allowed. Caller max_turns now caps runs; tool schema updates on next pi session."
|
|
6101
|
+
: "Per-call turn limits ignored. Configured agent/role and default budgets decide; the max_turns parameter is hidden on next pi session.");
|
|
6102
|
+
}
|
|
6103
|
+
}
|
|
3641
6104
|
else if (id === "graceTurns") {
|
|
3642
6105
|
const n = parseInt(value, 10);
|
|
3643
6106
|
if (n >= 1) {
|
|
@@ -3663,7 +6126,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3663
6126
|
setBackgroundByDefault(enabled);
|
|
3664
6127
|
notifyApplied(ctx, enabled
|
|
3665
6128
|
? "Agent calls run in the background unless they pass run_in_background: false"
|
|
3666
|
-
: "Agent calls
|
|
6129
|
+
: "Unqualified Agent calls now request foreground: the terminal UI yields immediately as a PENDING logical await and reports later; headless/print/RPC runs block and return inline");
|
|
3667
6130
|
}
|
|
3668
6131
|
else if (id === "schedulingEnabled") {
|
|
3669
6132
|
const enabled = value === "on";
|
|
@@ -3690,6 +6153,12 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3690
6153
|
notifyApplied(ctx, `Workflows ${enabled ? "enabled" : "disabled"}. Tool spec change takes effect on next pi session.`);
|
|
3691
6154
|
}
|
|
3692
6155
|
}
|
|
6156
|
+
else if (id === "workflowDefaultAgentType") {
|
|
6157
|
+
setWorkflowDefaultAgentType(value);
|
|
6158
|
+
// New runs only: a task freezes its default when it is created, which is
|
|
6159
|
+
// what lets a resume keep replaying under the role it started with.
|
|
6160
|
+
notifyApplied(ctx, `Workflow default agent set to ${value}`);
|
|
6161
|
+
}
|
|
3693
6162
|
else if (id === "scopeModels") {
|
|
3694
6163
|
const enabled = value === "on";
|
|
3695
6164
|
setScopeModelsEnabled(enabled);
|
|
@@ -3748,11 +6217,6 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3748
6217
|
setViewerMarkdown(value);
|
|
3749
6218
|
notifyApplied(ctx, `Viewer markdown set to ${value}`);
|
|
3750
6219
|
}
|
|
3751
|
-
else if (id === "fleetView") {
|
|
3752
|
-
const enabled = value === "on";
|
|
3753
|
-
setFleetViewEnabled(enabled);
|
|
3754
|
-
notifyApplied(ctx, `Fleet view ${enabled ? "enabled" : "disabled"}`);
|
|
3755
|
-
}
|
|
3756
6220
|
else if (id === "agentMentions") {
|
|
3757
6221
|
const mode = value;
|
|
3758
6222
|
setAgentMentionMode(mode);
|
|
@@ -3771,6 +6235,10 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3771
6235
|
setWidgetMode(value);
|
|
3772
6236
|
notifyApplied(ctx, `Widget set to ${value}`);
|
|
3773
6237
|
}
|
|
6238
|
+
else if (id === "widgetPlacement") {
|
|
6239
|
+
setWidgetPlacement(value);
|
|
6240
|
+
notifyApplied(ctx, `Widget placement set to ${value}`);
|
|
6241
|
+
}
|
|
3774
6242
|
}
|
|
3775
6243
|
let list;
|
|
3776
6244
|
// Track current selection index directly (SettingsList doesn't expose it).
|
|
@@ -3870,6 +6338,27 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3870
6338
|
description: "Manage agents",
|
|
3871
6339
|
handler: async (_args, ctx) => { await showAgentsMenu(ctx); },
|
|
3872
6340
|
});
|
|
6341
|
+
// Session-only "subagents off" — see force-main-model.ts for the semantics.
|
|
6342
|
+
pi.registerCommand("subagents", {
|
|
6343
|
+
description: "Force new subagents onto the main model (session only): /subagents on|off",
|
|
6344
|
+
handler: async (args, ctx) => {
|
|
6345
|
+
const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
6346
|
+
if (tokens[0]?.toLowerCase() === "cleanup") {
|
|
6347
|
+
await handleCleanupCommand(tokens.slice(1), ctx);
|
|
6348
|
+
return;
|
|
6349
|
+
}
|
|
6350
|
+
const arg = (args ?? "").trim().toLowerCase();
|
|
6351
|
+
if (arg !== "" && arg !== "on" && arg !== "off") {
|
|
6352
|
+
ctx.ui.notify("Usage: /subagents [on|off] — no argument toggles the current state.", "warning");
|
|
6353
|
+
return;
|
|
6354
|
+
}
|
|
6355
|
+
const next = arg === "" ? !isForceMainModel() : arg === "off";
|
|
6356
|
+
setForceMainModel(next);
|
|
6357
|
+
ctx.ui.notify(next
|
|
6358
|
+
? "Subagents OFF — new spawns, and anything they spawn, run on the main model until pi exits or /subagents on."
|
|
6359
|
+
: "Subagents ON — agent model pins and caller overrides apply again.", "info");
|
|
6360
|
+
},
|
|
6361
|
+
});
|
|
3873
6362
|
// The fleet overlay's third door: the same two-pane surface as `←` at an
|
|
3874
6363
|
// empty prompt and `/agents → Running agents`, reachable without the menu
|
|
3875
6364
|
// hop or an empty prompt. Registered unconditionally like `/agents` — the
|
|
@@ -3879,18 +6368,23 @@ Write the file using the write tool. Only write the file, nothing else.`;
|
|
|
3879
6368
|
description: "Open the agent fleet overlay",
|
|
3880
6369
|
handler: async (_args, ctx) => { await showFleetOverlay(ctx); },
|
|
3881
6370
|
});
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
6371
|
+
// Agent Hub chord (oh-my-pi's Alt+A). Opens the same overlay; Alt+A inside it closes it.
|
|
6372
|
+
// Hosts without a shortcut API keep `←` and /agent-fleet.
|
|
6373
|
+
if (typeof pi.registerShortcut === "function") {
|
|
6374
|
+
pi.registerShortcut("alt+a", {
|
|
6375
|
+
description: "Open the agent hub (fleet overlay)",
|
|
6376
|
+
handler: async (ctx) => {
|
|
6377
|
+
if (ctx.mode === "tui")
|
|
6378
|
+
await showFleetOverlay(ctx);
|
|
6379
|
+
},
|
|
6380
|
+
});
|
|
6381
|
+
}
|
|
6382
|
+
/** Shared inspector dependencies for `/agents → Workflows` and Agent Hub. */
|
|
3887
6383
|
const workflowMenuDeps = {
|
|
3888
6384
|
tasks: workflowTasks,
|
|
3889
6385
|
getRecord: id => manager.getRecord(id),
|
|
3890
6386
|
viewAgentConversation,
|
|
3891
|
-
// Read lazily: `currentCtx` is rebound on every session_start
|
|
3892
|
-
// fleet list may act between sessions, when there is none.
|
|
6387
|
+
// Read lazily: `currentCtx` is rebound on every session_start.
|
|
3893
6388
|
getCtx: () => currentCtx,
|
|
3894
6389
|
};
|
|
3895
|
-
fleet.setWorkflowSource(fleetWorkflows, id => openWorkflowFromFleet(id, workflowMenuDeps));
|
|
3896
6390
|
}
|