pi-subagent-manager 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +836 -0
- package/dist/index.js.map +1 -0
- package/dist/orch/checklist-integration.d.ts +48 -0
- package/dist/orch/checklist-integration.d.ts.map +1 -0
- package/dist/orch/checklist-integration.js +204 -0
- package/dist/orch/checklist-integration.js.map +1 -0
- package/dist/orch/context-entries.d.ts +8 -0
- package/dist/orch/context-entries.d.ts.map +1 -0
- package/dist/orch/context-entries.js +8 -0
- package/dist/orch/context-entries.js.map +1 -0
- package/dist/orch/cost-ledger.d.ts +16 -0
- package/dist/orch/cost-ledger.d.ts.map +1 -0
- package/dist/orch/cost-ledger.js +43 -0
- package/dist/orch/cost-ledger.js.map +1 -0
- package/dist/orch/diagnostics.d.ts +13 -0
- package/dist/orch/diagnostics.d.ts.map +1 -0
- package/dist/orch/diagnostics.js +95 -0
- package/dist/orch/diagnostics.js.map +1 -0
- package/dist/orch/extensions.d.ts +15 -0
- package/dist/orch/extensions.d.ts.map +1 -0
- package/dist/orch/extensions.js +80 -0
- package/dist/orch/extensions.js.map +1 -0
- package/dist/orch/housekeeping-usage.d.ts +14 -0
- package/dist/orch/housekeeping-usage.d.ts.map +1 -0
- package/dist/orch/housekeeping-usage.js +27 -0
- package/dist/orch/housekeeping-usage.js.map +1 -0
- package/dist/orch/housekeeping.d.ts +89 -0
- package/dist/orch/housekeeping.d.ts.map +1 -0
- package/dist/orch/housekeeping.js +281 -0
- package/dist/orch/housekeeping.js.map +1 -0
- package/dist/orch/inherited-tools.d.ts +18 -0
- package/dist/orch/inherited-tools.d.ts.map +1 -0
- package/dist/orch/inherited-tools.js +71 -0
- package/dist/orch/inherited-tools.js.map +1 -0
- package/dist/orch/mailbox.d.ts +59 -0
- package/dist/orch/mailbox.d.ts.map +1 -0
- package/dist/orch/mailbox.js +196 -0
- package/dist/orch/mailbox.js.map +1 -0
- package/dist/orch/manager.d.ts +82 -0
- package/dist/orch/manager.d.ts.map +1 -0
- package/dist/orch/manager.js +1010 -0
- package/dist/orch/manager.js.map +1 -0
- package/dist/orch/paths.d.ts +7 -0
- package/dist/orch/paths.d.ts.map +1 -0
- package/dist/orch/paths.js +73 -0
- package/dist/orch/paths.js.map +1 -0
- package/dist/orch/prompt.d.ts +7 -0
- package/dist/orch/prompt.d.ts.map +1 -0
- package/dist/orch/prompt.js +34 -0
- package/dist/orch/prompt.js.map +1 -0
- package/dist/orch/registry.d.ts +49 -0
- package/dist/orch/registry.d.ts.map +1 -0
- package/dist/orch/registry.js +134 -0
- package/dist/orch/registry.js.map +1 -0
- package/dist/orch/runtime.d.ts +11 -0
- package/dist/orch/runtime.d.ts.map +1 -0
- package/dist/orch/runtime.js +882 -0
- package/dist/orch/runtime.js.map +1 -0
- package/dist/orch/tools.d.ts +6 -0
- package/dist/orch/tools.d.ts.map +1 -0
- package/dist/orch/tools.js +114 -0
- package/dist/orch/tools.js.map +1 -0
- package/dist/orch/transcript.d.ts +28 -0
- package/dist/orch/transcript.d.ts.map +1 -0
- package/dist/orch/transcript.js +176 -0
- package/dist/orch/transcript.js.map +1 -0
- package/dist/prefs/agent-import.d.ts +37 -0
- package/dist/prefs/agent-import.d.ts.map +1 -0
- package/dist/prefs/agent-import.js +196 -0
- package/dist/prefs/agent-import.js.map +1 -0
- package/dist/prefs/config.d.ts +108 -0
- package/dist/prefs/config.d.ts.map +1 -0
- package/dist/prefs/config.js +926 -0
- package/dist/prefs/config.js.map +1 -0
- package/dist/prefs/import-discovery.d.ts +28 -0
- package/dist/prefs/import-discovery.d.ts.map +1 -0
- package/dist/prefs/import-discovery.js +562 -0
- package/dist/prefs/import-discovery.js.map +1 -0
- package/dist/prefs/import-instructions.d.ts +3 -0
- package/dist/prefs/import-instructions.d.ts.map +1 -0
- package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +1 -0
- package/dist/prefs/import-instructions.js.map +1 -0
- package/dist/prefs/models.d.ts +24 -0
- package/dist/prefs/models.d.ts.map +1 -0
- package/dist/prefs/models.js +57 -0
- package/dist/prefs/models.js.map +1 -0
- package/dist/prefs/settings.d.ts +89 -0
- package/dist/prefs/settings.d.ts.map +1 -0
- package/dist/prefs/settings.js +505 -0
- package/dist/prefs/settings.js.map +1 -0
- package/dist/types.d.ts +293 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/ui/agent-loader.d.ts +21 -0
- package/dist/ui/agent-loader.d.ts.map +1 -0
- package/dist/ui/agent-loader.js +73 -0
- package/dist/ui/agent-loader.js.map +1 -0
- package/dist/ui/agent-navigation-editor.d.ts +46 -0
- package/dist/ui/agent-navigation-editor.d.ts.map +1 -0
- package/dist/ui/agent-navigation-editor.js +189 -0
- package/dist/ui/agent-navigation-editor.js.map +1 -0
- package/dist/ui/cost-footer.d.ts +37 -0
- package/dist/ui/cost-footer.d.ts.map +1 -0
- package/dist/ui/cost-footer.js +215 -0
- package/dist/ui/cost-footer.js.map +1 -0
- package/dist/ui/dialog.d.ts +135 -0
- package/dist/ui/dialog.d.ts.map +1 -0
- package/dist/ui/dialog.js +533 -0
- package/dist/ui/dialog.js.map +1 -0
- package/dist/ui/import-picker.d.ts +38 -0
- package/dist/ui/import-picker.d.ts.map +1 -0
- package/dist/ui/import-picker.js +211 -0
- package/dist/ui/import-picker.js.map +1 -0
- package/dist/ui/live-agent-view.d.ts +82 -0
- package/dist/ui/live-agent-view.d.ts.map +1 -0
- package/dist/ui/live-agent-view.js +546 -0
- package/dist/ui/live-agent-view.js.map +1 -0
- package/dist/ui/model-picker.d.ts +109 -0
- package/dist/ui/model-picker.d.ts.map +1 -0
- package/dist/ui/model-picker.js +549 -0
- package/dist/ui/model-picker.js.map +1 -0
- package/dist/ui/settings-ui.d.ts +17 -0
- package/dist/ui/settings-ui.d.ts.map +1 -0
- package/dist/ui/settings-ui.js +679 -0
- package/dist/ui/settings-ui.js.map +1 -0
- package/dist/ui/status-ui.d.ts +67 -0
- package/dist/ui/status-ui.d.ts.map +1 -0
- package/dist/ui/status-ui.js +487 -0
- package/dist/ui/status-ui.js.map +1 -0
- package/dist/ui/thread-tree.d.ts +22 -0
- package/dist/ui/thread-tree.d.ts.map +1 -0
- package/dist/ui/thread-tree.js +153 -0
- package/dist/ui/thread-tree.js.map +1 -0
- package/dist/ui/tool-picker.d.ts +46 -0
- package/dist/ui/tool-picker.d.ts.map +1 -0
- package/dist/ui/tool-picker.js +334 -0
- package/dist/ui/tool-picker.js.map +1 -0
- package/dist/ui/transcript-tool.d.ts +2 -0
- package/dist/ui/transcript-tool.d.ts.map +1 -0
- package/dist/ui/transcript-tool.js +100 -0
- package/dist/ui/transcript-tool.js.map +1 -0
- package/dist/ui/ui.d.ts +41 -0
- package/dist/ui/ui.d.ts.map +1 -0
- package/dist/ui/ui.js +1047 -0
- package/dist/ui/ui.js.map +1 -0
- package/docs/development.md +2 -1
- package/package.json +16 -4
- package/src/index.ts +0 -920
- package/src/orch/checklist-integration.ts +0 -230
- package/src/orch/context-entries.ts +0 -15
- package/src/orch/cost-ledger.ts +0 -56
- package/src/orch/diagnostics.ts +0 -95
- package/src/orch/extensions.ts +0 -83
- package/src/orch/housekeeping-usage.ts +0 -47
- package/src/orch/housekeeping.ts +0 -348
- package/src/orch/inherited-tools.ts +0 -84
- package/src/orch/mailbox.ts +0 -261
- package/src/orch/manager.ts +0 -1084
- package/src/orch/paths.ts +0 -73
- package/src/orch/prompt.ts +0 -39
- package/src/orch/registry.ts +0 -168
- package/src/orch/runtime.ts +0 -1041
- package/src/orch/tools.ts +0 -190
- package/src/orch/transcript.ts +0 -186
- package/src/prefs/agent-import.ts +0 -245
- package/src/prefs/config.ts +0 -1017
- package/src/prefs/import-discovery.ts +0 -643
- package/src/prefs/models.ts +0 -74
- package/src/prefs/settings.ts +0 -614
- package/src/types.ts +0 -271
- package/src/ui/agent-loader.ts +0 -98
- package/src/ui/agent-navigation-editor.ts +0 -233
- package/src/ui/cost-footer.ts +0 -230
- package/src/ui/dialog.ts +0 -678
- package/src/ui/import-picker.ts +0 -231
- package/src/ui/live-agent-view.ts +0 -600
- package/src/ui/model-picker.ts +0 -701
- package/src/ui/settings-ui.ts +0 -830
- package/src/ui/status-ui.ts +0 -628
- package/src/ui/thread-tree.ts +0 -173
- package/src/ui/tool-picker.ts +0 -398
- package/src/ui/transcript-tool.ts +0 -142
- package/src/ui/ui.ts +0 -1407
package/src/index.ts
DELETED
|
@@ -1,920 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
CAPABILITY_PROBE_CHANNEL,
|
|
3
|
-
respondDiagnosticCapability,
|
|
4
|
-
diagnosticAgentText,
|
|
5
|
-
} from "./orch/diagnostics.ts";
|
|
6
|
-
import { randomUUID } from "node:crypto";
|
|
7
|
-
import { buildSessionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
8
|
-
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
9
|
-
import { fuzzyFilter } from "@earendil-works/pi-tui";
|
|
10
|
-
import { ConfigStore } from "./prefs/config.ts";
|
|
11
|
-
import {
|
|
12
|
-
IMPORT_REQUEST_PREFIX,
|
|
13
|
-
markImportOffered,
|
|
14
|
-
offerAgentImport,
|
|
15
|
-
} from "./prefs/agent-import.ts";
|
|
16
|
-
import { ThreadManager } from "./orch/manager.ts";
|
|
17
|
-
import { inheritedContextEntries } from "./orch/context-entries.ts";
|
|
18
|
-
import { loadManagerSettings } from "./prefs/settings.ts";
|
|
19
|
-
import { configureAgents } from "./ui/settings-ui.ts";
|
|
20
|
-
import { AgentNavigationController } from "./ui/status-ui.ts";
|
|
21
|
-
import { AgentNavigationEditor } from "./ui/agent-navigation-editor.ts";
|
|
22
|
-
import { createDriverFactory } from "./orch/runtime.ts";
|
|
23
|
-
import {
|
|
24
|
-
createHousekeepingCompleter,
|
|
25
|
-
HousekeepingSummarizer,
|
|
26
|
-
resolveHousekeepingModel,
|
|
27
|
-
} from "./orch/housekeeping.ts";
|
|
28
|
-
import { createInheritedToolSource } from "./orch/inherited-tools.ts";
|
|
29
|
-
import { subagentPrompt } from "./orch/prompt.ts";
|
|
30
|
-
import { ChecklistMetaMirror, checklistStatus } from "./orch/checklist-integration.ts";
|
|
31
|
-
import { agentTools } from "./orch/tools.ts";
|
|
32
|
-
import { editAgentTypes, updateWidget } from "./ui/ui.ts";
|
|
33
|
-
import { canOpenDialog, dialogMenu } from "./ui/dialog.ts";
|
|
34
|
-
import type { ThreadEvent, ThreadView } from "./types.ts";
|
|
35
|
-
import { COST_ENTRY, CostLedger } from "./orch/cost-ledger.ts";
|
|
36
|
-
import { readRegistry, RegistryWriter } from "./orch/registry.ts";
|
|
37
|
-
import { CostFooterController } from "./ui/cost-footer.ts";
|
|
38
|
-
|
|
39
|
-
const ROOT_MAILBOX_ENTRY = "pi-subagent:root-mailbox:v1";
|
|
40
|
-
const ROOT_SUMMARY_MESSAGE = "pi-subagent:final-recap";
|
|
41
|
-
const ROOT_WAKE_MESSAGE = "pi-subagent:wake";
|
|
42
|
-
type RootNotification = {
|
|
43
|
-
rootSessionId: string;
|
|
44
|
-
content: string;
|
|
45
|
-
finalRecap?: boolean;
|
|
46
|
-
/** Start a main-agent turn so it reacts to this event (async completion, spawn timeout). */
|
|
47
|
-
trigger?: boolean;
|
|
48
|
-
details: { mailboxId: string; path: string; state: string };
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
export default function piSubagent(pi: ExtensionAPI): void {
|
|
52
|
-
let capabilityActive = true;
|
|
53
|
-
pi.events.on(CAPABILITY_PROBE_CHANNEL, (payload) => {
|
|
54
|
-
if (capabilityActive && limits.subagentMode !== "off") respondDiagnosticCapability(payload);
|
|
55
|
-
});
|
|
56
|
-
let context: ExtensionContext | undefined;
|
|
57
|
-
const inheritedTools = createInheritedToolSource(pi);
|
|
58
|
-
let store = new ConfigStore({
|
|
59
|
-
cwd: process.cwd(),
|
|
60
|
-
agentDir: getAgentDir(),
|
|
61
|
-
includeProject: false,
|
|
62
|
-
});
|
|
63
|
-
let manager: ThreadManager | undefined;
|
|
64
|
-
let costLedger = new CostLedger();
|
|
65
|
-
const costFooter = new CostFooterController(
|
|
66
|
-
pi,
|
|
67
|
-
() => costLedger.totalUsd,
|
|
68
|
-
() => limits.nerdFontIcons,
|
|
69
|
-
() => limits.costDisplay,
|
|
70
|
-
() => limits.costValue,
|
|
71
|
-
() => limits.costIcon,
|
|
72
|
-
);
|
|
73
|
-
const refreshCostFooter = (ctx: ExtensionContext) => costFooter.refresh(ctx);
|
|
74
|
-
const rollupCost = (thread: ThreadView) => {
|
|
75
|
-
costLedger.settle(thread, (record) => pi.appendEntry(COST_ENTRY, record));
|
|
76
|
-
if (context) refreshCostFooter(context);
|
|
77
|
-
};
|
|
78
|
-
let limits = loadManagerSettings({
|
|
79
|
-
cwd: process.cwd(),
|
|
80
|
-
agentDir: getAgentDir(),
|
|
81
|
-
includeProject: false,
|
|
82
|
-
}).settings;
|
|
83
|
-
// [labs] Housekeeping: inert unless opted in, a model is chosen, and it resolves with credentials.
|
|
84
|
-
const housekeeping = new HousekeepingSummarizer({
|
|
85
|
-
isEnabled: () =>
|
|
86
|
-
limits.subagentMode !== "off" &&
|
|
87
|
-
limits.housekeepingEnabled &&
|
|
88
|
-
limits.housekeepingModel !== "" &&
|
|
89
|
-
context !== undefined &&
|
|
90
|
-
resolveHousekeepingModel(context, limits.housekeepingModel) !== undefined,
|
|
91
|
-
complete: createHousekeepingCompleter(
|
|
92
|
-
() => context,
|
|
93
|
-
() => limits.housekeepingModel,
|
|
94
|
-
refreshCostFooter,
|
|
95
|
-
),
|
|
96
|
-
apply: (path, run, summary) => manager?.setSummary(path, run, summary) ?? false,
|
|
97
|
-
clear: (path, run) => void manager?.clearSummary(path, run),
|
|
98
|
-
onFailure: (message) =>
|
|
99
|
-
context?.ui.notify(
|
|
100
|
-
`Housekeeping summaries failed (${message}); showing normal agent status instead.`,
|
|
101
|
-
"warning",
|
|
102
|
-
),
|
|
103
|
-
});
|
|
104
|
-
let housekeepingKey = "";
|
|
105
|
-
/** Settings changed: drop in-flight work and stale summaries so the new choice starts clean. */
|
|
106
|
-
const syncHousekeeping = () => {
|
|
107
|
-
const key = `${limits.subagentMode === "off"}|${limits.housekeepingEnabled}|${limits.housekeepingModel}`;
|
|
108
|
-
if (key === housekeepingKey) return;
|
|
109
|
-
housekeepingKey = key;
|
|
110
|
-
housekeeping.cancelAll();
|
|
111
|
-
manager?.clearSummaries();
|
|
112
|
-
};
|
|
113
|
-
const loadLimits = (ctx: ExtensionContext) => {
|
|
114
|
-
const loaded = loadManagerSettings({
|
|
115
|
-
cwd: ctx.cwd,
|
|
116
|
-
agentDir: getAgentDir(),
|
|
117
|
-
includeProject: ctx.isProjectTrusted(),
|
|
118
|
-
});
|
|
119
|
-
limits = loaded.settings;
|
|
120
|
-
syncHousekeeping();
|
|
121
|
-
refreshCostFooter(ctx);
|
|
122
|
-
return loaded.diagnostics;
|
|
123
|
-
};
|
|
124
|
-
const checklistMirror = new ChecklistMetaMirror(() => getAgentDir());
|
|
125
|
-
const currentChecklistStatus = (ctx: ExtensionContext) =>
|
|
126
|
-
checklistStatus(pi, checklistMirror, ctx);
|
|
127
|
-
let generation = 0;
|
|
128
|
-
let rootTurnEnded = false;
|
|
129
|
-
const hiddenWidgetThreads = new Set<string>();
|
|
130
|
-
let widgetCollapsed = false;
|
|
131
|
-
let rootTurnRunning = false;
|
|
132
|
-
let suspendingSummaries = false;
|
|
133
|
-
// One arbiter owns both timeout wakes and completion/continuation turns.
|
|
134
|
-
let rootTurnTimer: ReturnType<typeof setTimeout> | undefined;
|
|
135
|
-
let wakeRequested = false;
|
|
136
|
-
const cancelSummary = () => {
|
|
137
|
-
if (rootTurnTimer !== undefined) clearTimeout(rootTurnTimer);
|
|
138
|
-
rootTurnTimer = undefined;
|
|
139
|
-
wakeRequested = false;
|
|
140
|
-
rootTurnRunning = false;
|
|
141
|
-
};
|
|
142
|
-
// Right at a tree leaf steps tree → full: leave any session collapse behind.
|
|
143
|
-
const returnToWidget = () => {
|
|
144
|
-
if (!widgetCollapsed) return;
|
|
145
|
-
widgetCollapsed = false;
|
|
146
|
-
if (context) refreshWidget(context);
|
|
147
|
-
};
|
|
148
|
-
let navigation = new AgentNavigationController(returnToWidget);
|
|
149
|
-
let navigationEditor: AgentNavigationEditor | undefined;
|
|
150
|
-
let navigationEditorFactory: Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0];
|
|
151
|
-
let navigationGeneration = 0;
|
|
152
|
-
const closeNavigation = (disposeEditor = false) => {
|
|
153
|
-
navigationGeneration++;
|
|
154
|
-
navigation.close();
|
|
155
|
-
if (disposeEditor) {
|
|
156
|
-
navigationEditor?.dispose();
|
|
157
|
-
navigationEditor = undefined;
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
const installNavigationEditor = (ctx: ExtensionContext, seedHistory: boolean) => {
|
|
161
|
-
// Pi has one custom-editor slot: do not replace another integration.
|
|
162
|
-
if (!ctx.hasUI || ctx.mode !== "tui" || !ctx.ui.setEditorComponent) return;
|
|
163
|
-
const existingFactory = ctx.ui.getEditorComponent?.();
|
|
164
|
-
if (existingFactory && existingFactory !== navigationEditorFactory) return;
|
|
165
|
-
// The host only transfers raw text, not cursor/undo/expanded-paste state.
|
|
166
|
-
if (ctx.ui.getEditorText?.()) return;
|
|
167
|
-
const history = buildSessionContext(ctx.sessionManager.getBranch()).messages.flatMap(
|
|
168
|
-
(message) => {
|
|
169
|
-
if (message.role !== "user") return [];
|
|
170
|
-
const content = message.content;
|
|
171
|
-
return [
|
|
172
|
-
typeof content === "string"
|
|
173
|
-
? content
|
|
174
|
-
: content
|
|
175
|
-
.filter((block) => block.type === "text")
|
|
176
|
-
.map((block) => block.text)
|
|
177
|
-
.join(""),
|
|
178
|
-
];
|
|
179
|
-
},
|
|
180
|
-
);
|
|
181
|
-
navigationEditorFactory = (tui, theme, keys) => {
|
|
182
|
-
const editor = new AgentNavigationEditor(tui, theme, keys, {
|
|
183
|
-
// Initial startup hydrates after session_start; replacement editors do not.
|
|
184
|
-
initialHistory: seedHistory ? history : undefined,
|
|
185
|
-
generation: () => navigationGeneration,
|
|
186
|
-
canOpen: () =>
|
|
187
|
-
manager !== undefined &&
|
|
188
|
-
context?.mode === "tui" &&
|
|
189
|
-
limits.subagentMode !== "off" &&
|
|
190
|
-
!navigation.isOpen &&
|
|
191
|
-
manager
|
|
192
|
-
.list()
|
|
193
|
-
.some(
|
|
194
|
-
(thread) =>
|
|
195
|
-
thread.path !== "/root" &&
|
|
196
|
-
(thread.state === "starting" || thread.state === "running"),
|
|
197
|
-
),
|
|
198
|
-
openTree: () =>
|
|
199
|
-
manager && context
|
|
200
|
-
? navigation.open(
|
|
201
|
-
context,
|
|
202
|
-
manager.scope("/root"),
|
|
203
|
-
undefined,
|
|
204
|
-
limits.nerdFontIcons,
|
|
205
|
-
limits.loaderStyle,
|
|
206
|
-
)
|
|
207
|
-
: undefined,
|
|
208
|
-
canCollapse: () =>
|
|
209
|
-
manager !== undefined &&
|
|
210
|
-
context?.mode === "tui" &&
|
|
211
|
-
limits.subagentMode !== "off" &&
|
|
212
|
-
!navigation.isOpen &&
|
|
213
|
-
!widgetCollapsed &&
|
|
214
|
-
limits.widgetMode === "full" &&
|
|
215
|
-
widgetThreads().some((thread) => thread.path !== "/root"),
|
|
216
|
-
collapseWidget: () => {
|
|
217
|
-
widgetCollapsed = true;
|
|
218
|
-
if (context) refreshWidget(context);
|
|
219
|
-
},
|
|
220
|
-
// Left from the session-collapsed one-liner returns to full before the tree.
|
|
221
|
-
canExpand: () =>
|
|
222
|
-
manager !== undefined &&
|
|
223
|
-
context?.mode === "tui" &&
|
|
224
|
-
limits.subagentMode !== "off" &&
|
|
225
|
-
!navigation.isOpen &&
|
|
226
|
-
widgetCollapsed &&
|
|
227
|
-
limits.widgetMode === "full" &&
|
|
228
|
-
widgetThreads().some((thread) => thread.path !== "/root"),
|
|
229
|
-
expandWidget: () => {
|
|
230
|
-
widgetCollapsed = false;
|
|
231
|
-
if (context) refreshWidget(context);
|
|
232
|
-
},
|
|
233
|
-
onError: (error) =>
|
|
234
|
-
context?.ui.notify(error instanceof Error ? error.message : String(error), "error"),
|
|
235
|
-
});
|
|
236
|
-
navigationEditor = editor;
|
|
237
|
-
return editor;
|
|
238
|
-
};
|
|
239
|
-
ctx.ui.setEditorComponent(navigationEditorFactory);
|
|
240
|
-
};
|
|
241
|
-
const registryWriter = new RegistryWriter((customType, data) => pi.appendEntry(customType, data));
|
|
242
|
-
let migrationRequested = false;
|
|
243
|
-
let importInProgress = false;
|
|
244
|
-
const importAgents = async (ctx: ExtensionContext, firstRun: boolean) => {
|
|
245
|
-
// Migration requires the root's file tools and must not delegate source prompts.
|
|
246
|
-
if (limits.subagentMode === "orchestration") {
|
|
247
|
-
if (!firstRun)
|
|
248
|
-
ctx.ui.notify(
|
|
249
|
-
"Agent import requires Opportunistic mode. Change Subagent Mode in /agents settings.",
|
|
250
|
-
"info",
|
|
251
|
-
);
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
if (importInProgress) return;
|
|
255
|
-
importInProgress = true;
|
|
256
|
-
try {
|
|
257
|
-
migrationRequested =
|
|
258
|
-
(await offerAgentImport(pi, ctx, {
|
|
259
|
-
agentDir: getAgentDir(),
|
|
260
|
-
store,
|
|
261
|
-
firstRun,
|
|
262
|
-
})) || migrationRequested;
|
|
263
|
-
} finally {
|
|
264
|
-
importInProgress = false;
|
|
265
|
-
}
|
|
266
|
-
};
|
|
267
|
-
const requireManager = () => {
|
|
268
|
-
if (!manager) throw new Error("Subagent threads are not initialized; start a Pi session first");
|
|
269
|
-
return manager;
|
|
270
|
-
};
|
|
271
|
-
const widgetThreads = () =>
|
|
272
|
-
requireManager()
|
|
273
|
-
.list()
|
|
274
|
-
.filter((thread) => {
|
|
275
|
-
// Resuming a retained session makes it visible for this task, even after it settles again.
|
|
276
|
-
if (thread.state === "starting" || thread.state === "running")
|
|
277
|
-
hiddenWidgetThreads.delete(thread.path);
|
|
278
|
-
return !hiddenWidgetThreads.has(thread.path);
|
|
279
|
-
});
|
|
280
|
-
const requireContext = () => {
|
|
281
|
-
if (!context) throw new Error("No active Pi session");
|
|
282
|
-
return context;
|
|
283
|
-
};
|
|
284
|
-
const persist = () => {
|
|
285
|
-
if (!manager) return;
|
|
286
|
-
registryWriter.write(requireContext().sessionManager.getSessionId(), manager.saved());
|
|
287
|
-
};
|
|
288
|
-
const warnDelivery = (error: unknown) => {
|
|
289
|
-
if (limits.subagentMode === "off") return;
|
|
290
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
291
|
-
context?.ui.notify(`Subagent delivery failed: ${message}`, "warning");
|
|
292
|
-
};
|
|
293
|
-
const sendRootNotification = (notification: RootNotification) => {
|
|
294
|
-
if (limits.subagentMode === "off" || context?.isIdle?.() === false) return;
|
|
295
|
-
// Never submit to Pi's streaming queue: off must also suppress pending delivery.
|
|
296
|
-
pi.sendMessage(
|
|
297
|
-
{
|
|
298
|
-
customType: "pi-subagent:update",
|
|
299
|
-
content: notification.content,
|
|
300
|
-
// Keep asynchronous child updates in model context, not the main chat.
|
|
301
|
-
// Idle/settlement delivery can follow the root's final answer; rendering it
|
|
302
|
-
// would leave a child's output as the last visible message. The widget and
|
|
303
|
-
// agent browser provide status/output without displacing the root response.
|
|
304
|
-
display: false,
|
|
305
|
-
details: notification.details,
|
|
306
|
-
},
|
|
307
|
-
{ triggerTurn: false },
|
|
308
|
-
);
|
|
309
|
-
if (notification.trigger === true) wakeRequested = true;
|
|
310
|
-
};
|
|
311
|
-
const pendingSummaries = (ctx: ExtensionContext) => {
|
|
312
|
-
const entries = ctx.sessionManager.getBranch();
|
|
313
|
-
const summarized = new Set(
|
|
314
|
-
entries.flatMap((entry) => {
|
|
315
|
-
if (entry.type !== "custom_message" || entry.customType !== ROOT_SUMMARY_MESSAGE) return [];
|
|
316
|
-
const ids = (entry.details as { mailboxIds?: unknown } | undefined)?.mailboxIds;
|
|
317
|
-
return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
|
|
318
|
-
}),
|
|
319
|
-
);
|
|
320
|
-
return entries.flatMap((entry) => {
|
|
321
|
-
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
|
|
322
|
-
const notification = entry.data as RootNotification | undefined;
|
|
323
|
-
return notification?.rootSessionId === ctx.sessionManager.getSessionId() &&
|
|
324
|
-
notification.finalRecap === true &&
|
|
325
|
-
typeof notification.content === "string" &&
|
|
326
|
-
typeof notification.details?.mailboxId === "string" &&
|
|
327
|
-
!summarized.has(notification.details.mailboxId)
|
|
328
|
-
? [notification]
|
|
329
|
-
: [];
|
|
330
|
-
});
|
|
331
|
-
};
|
|
332
|
-
const pendingRootNotifications = (ctx: ExtensionContext) => {
|
|
333
|
-
const entries = ctx.sessionManager.getBranch();
|
|
334
|
-
const delivered = new Set(
|
|
335
|
-
entries.flatMap((entry) => {
|
|
336
|
-
if (entry.type !== "custom_message" || entry.customType !== "pi-subagent:update") return [];
|
|
337
|
-
const id = (entry.details as { mailboxId?: unknown } | undefined)?.mailboxId;
|
|
338
|
-
return typeof id === "string" ? [id] : [];
|
|
339
|
-
}),
|
|
340
|
-
);
|
|
341
|
-
return entries.flatMap((entry) => {
|
|
342
|
-
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
|
|
343
|
-
const notification = entry.data as RootNotification | undefined;
|
|
344
|
-
if (
|
|
345
|
-
notification?.rootSessionId !== ctx.sessionManager.getSessionId() ||
|
|
346
|
-
typeof notification.content !== "string" ||
|
|
347
|
-
typeof notification.details?.mailboxId !== "string" ||
|
|
348
|
-
delivered.has(notification.details.mailboxId)
|
|
349
|
-
)
|
|
350
|
-
return [];
|
|
351
|
-
delivered.add(notification.details.mailboxId);
|
|
352
|
-
return [notification];
|
|
353
|
-
});
|
|
354
|
-
};
|
|
355
|
-
const scheduleRootTurn = (ctx: ExtensionContext) => {
|
|
356
|
-
if (
|
|
357
|
-
limits.subagentMode === "off" ||
|
|
358
|
-
rootTurnRunning ||
|
|
359
|
-
suspendingSummaries ||
|
|
360
|
-
rootTurnTimer !== undefined
|
|
361
|
-
)
|
|
362
|
-
return;
|
|
363
|
-
// Include undelivered mailbox entries: a completion may arrive while Pi is
|
|
364
|
-
// compacting, which does not necessarily produce an agent_settled event.
|
|
365
|
-
if (
|
|
366
|
-
!wakeRequested &&
|
|
367
|
-
!(
|
|
368
|
-
limits.finalRecap &&
|
|
369
|
-
(manager?.outstandingAsync() ?? 0) === 0 &&
|
|
370
|
-
pendingSummaries(ctx).length > 0
|
|
371
|
-
) &&
|
|
372
|
-
!pendingRootNotifications(ctx).some((notification) => notification.trigger === true)
|
|
373
|
-
)
|
|
374
|
-
return;
|
|
375
|
-
const currentGeneration = generation;
|
|
376
|
-
// Zero-delay deferral crosses the SDK settlement boundary; busy retries also
|
|
377
|
-
// cover compaction and other non-agent busy periods. Reporting timers are
|
|
378
|
-
// deliberately irrelevant to completion readiness.
|
|
379
|
-
rootTurnTimer = setTimeout(
|
|
380
|
-
() => {
|
|
381
|
-
rootTurnTimer = undefined;
|
|
382
|
-
if (
|
|
383
|
-
currentGeneration !== generation ||
|
|
384
|
-
context?.sessionManager !== ctx.sessionManager ||
|
|
385
|
-
limits.subagentMode === "off" ||
|
|
386
|
-
suspendingSummaries ||
|
|
387
|
-
rootTurnRunning
|
|
388
|
-
)
|
|
389
|
-
return;
|
|
390
|
-
if (ctx.isIdle() === false) {
|
|
391
|
-
scheduleRootTurn(ctx);
|
|
392
|
-
return;
|
|
393
|
-
}
|
|
394
|
-
drainRootMailbox(ctx);
|
|
395
|
-
const notifications =
|
|
396
|
-
limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0
|
|
397
|
-
? pendingSummaries(ctx)
|
|
398
|
-
: [];
|
|
399
|
-
if (!notifications.length && !wakeRequested) return;
|
|
400
|
-
const wasWakeRequested = wakeRequested;
|
|
401
|
-
wakeRequested = false;
|
|
402
|
-
rootTurnRunning = true; // Also reserves a normal wake until agent_settled.
|
|
403
|
-
try {
|
|
404
|
-
pi.sendMessage(
|
|
405
|
-
notifications.length
|
|
406
|
-
? {
|
|
407
|
-
customType: ROOT_SUMMARY_MESSAGE,
|
|
408
|
-
content:
|
|
409
|
-
"The asynchronous subagent batch has finished. Collect and inspect its results " +
|
|
410
|
-
"(use agent_output if more detail is needed), then continue any unfinished work in the user's task. " +
|
|
411
|
-
"If the overall task is complete, give a concise final recap covering results and failures. " +
|
|
412
|
-
"Do not spawn or resume agents solely to summarize.\nAgents: " +
|
|
413
|
-
[
|
|
414
|
-
...new Set(notifications.map((notification) => notification.details.path)),
|
|
415
|
-
].join(", "),
|
|
416
|
-
display: false,
|
|
417
|
-
details: {
|
|
418
|
-
mailboxIds: notifications.map((notification) => notification.details.mailboxId),
|
|
419
|
-
},
|
|
420
|
-
}
|
|
421
|
-
: {
|
|
422
|
-
customType: ROOT_WAKE_MESSAGE,
|
|
423
|
-
content:
|
|
424
|
-
"Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
|
|
425
|
-
"Collect results with agent_output and continue any unfinished work; recap when the overall task is complete. " +
|
|
426
|
-
"For a timeout event decide to wait, steer, stop or re-arm with agent_steer using path and timeoutMs only " +
|
|
427
|
-
"(omit message; resets the reporting timer from now without interrupting the running agent).",
|
|
428
|
-
display: false,
|
|
429
|
-
details: {},
|
|
430
|
-
},
|
|
431
|
-
{ triggerTurn: true },
|
|
432
|
-
);
|
|
433
|
-
} catch (error) {
|
|
434
|
-
rootTurnRunning = false;
|
|
435
|
-
wakeRequested = wasWakeRequested;
|
|
436
|
-
warnDelivery(error);
|
|
437
|
-
}
|
|
438
|
-
},
|
|
439
|
-
ctx.isIdle() === false ? 100 : 0,
|
|
440
|
-
);
|
|
441
|
-
rootTurnTimer.unref?.();
|
|
442
|
-
};
|
|
443
|
-
const drainRootMailbox = (ctx: ExtensionContext) => {
|
|
444
|
-
if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
|
|
445
|
-
for (const notification of pendingRootNotifications(ctx)) sendRootNotification(notification);
|
|
446
|
-
};
|
|
447
|
-
const restoreRootMailbox = (ctx: ExtensionContext) => {
|
|
448
|
-
drainRootMailbox(ctx);
|
|
449
|
-
scheduleRootTurn(ctx);
|
|
450
|
-
};
|
|
451
|
-
pi.on("agent_settled", async (_event, ctx) => {
|
|
452
|
-
if (context?.sessionManager === ctx.sessionManager) {
|
|
453
|
-
rootTurnRunning = false;
|
|
454
|
-
restoreRootMailbox(ctx);
|
|
455
|
-
}
|
|
456
|
-
});
|
|
457
|
-
const delivery = (event: ThreadEvent) => {
|
|
458
|
-
if (event.kind === "change" || event.kind === "metrics") return;
|
|
459
|
-
const thread = event.thread;
|
|
460
|
-
const fmtMs = (ms: number) => `${Math.round(ms / 1000)}s`;
|
|
461
|
-
const elapsed =
|
|
462
|
-
(thread.elapsedMs ?? 0) + (thread.startedAt ? Date.now() - thread.startedAt : 0);
|
|
463
|
-
const message =
|
|
464
|
-
event.kind === "diagnostic"
|
|
465
|
-
? diagnosticAgentText(thread.path, event.diagnostic)
|
|
466
|
-
: event.kind === "update"
|
|
467
|
-
? `Progress from ${thread.path}: ${event.message}`
|
|
468
|
-
: event.kind === "timeout"
|
|
469
|
-
? `Agent ${thread.path} hit its ${fmtMs(event.timeoutMs)} spawn timeout and is STILL RUNNING (not stopped). ` +
|
|
470
|
-
`State: ${thread.state}; status: ${thread.status}; elapsed: ${fmtMs(elapsed)}; ` +
|
|
471
|
-
`tokens: ${thread.inputTokens ?? 0} in / ${thread.outputTokens ?? 0} out.\n` +
|
|
472
|
-
`Recent output:\n${event.recentOutput || "(none yet)"}\n` +
|
|
473
|
-
"Decide: agent_steer with timeoutMs only (no message) to be notified again later without disturbing it, agent_wait for it, agent_steer to redirect, agent_stop to cancel, or let it continue."
|
|
474
|
-
: thread.state === "completed"
|
|
475
|
-
? `Agent ${thread.path} completed. Final answer:\n${thread.output?.slice(0, 16000) ?? "(no text)"}${(thread.output?.length ?? 0) > 16000 ? "\n[Output truncated; use agent_output for more.]" : ""}`
|
|
476
|
-
: `Agent ${thread.path} is ${thread.state}: ${thread.status}. ${thread.state === "paused" ? "No answer handback; send input to resume the same session." : "Session retained for further input."}`;
|
|
477
|
-
try {
|
|
478
|
-
if (event.recipient === "/root") {
|
|
479
|
-
const recap =
|
|
480
|
-
limits.finalRecap &&
|
|
481
|
-
!suspendingSummaries &&
|
|
482
|
-
event.kind === "settled" &&
|
|
483
|
-
event.async &&
|
|
484
|
-
["completed", "failed", "stopped"].includes(thread.state);
|
|
485
|
-
const notification: RootNotification = {
|
|
486
|
-
rootSessionId: requireContext().sessionManager.getSessionId(),
|
|
487
|
-
content: message,
|
|
488
|
-
// Foreground results already handled by a busy main thread do not need
|
|
489
|
-
// another turn. Completions during a summary do need a follow-up summary.
|
|
490
|
-
finalRecap: recap,
|
|
491
|
-
// Recap mode defers the turn until every outstanding async agent has reported.
|
|
492
|
-
trigger:
|
|
493
|
-
!suspendingSummaries &&
|
|
494
|
-
(event.kind === "timeout" || (event.kind === "settled" && event.async && !recap)),
|
|
495
|
-
details: {
|
|
496
|
-
mailboxId: randomUUID(),
|
|
497
|
-
path: thread.path,
|
|
498
|
-
state: thread.state,
|
|
499
|
-
},
|
|
500
|
-
};
|
|
501
|
-
// Persist first; defer delivery until the root is idle and the plugin is enabled.
|
|
502
|
-
// The eventual transcript message carries its ID for branch-local recovery.
|
|
503
|
-
pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
|
|
504
|
-
restoreRootMailbox(requireContext());
|
|
505
|
-
} else {
|
|
506
|
-
void requireManager().deliver(event.recipient, message).catch(warnDelivery);
|
|
507
|
-
// Global outstandingAsync includes nested descendants, so their last
|
|
508
|
-
// settlement must unblock a root batch even when its parent has finished.
|
|
509
|
-
if (event.kind === "settled") restoreRootMailbox(requireContext());
|
|
510
|
-
}
|
|
511
|
-
} catch (error) {
|
|
512
|
-
warnDelivery(error);
|
|
513
|
-
}
|
|
514
|
-
};
|
|
515
|
-
|
|
516
|
-
const makeDriverFactory = () =>
|
|
517
|
-
createDriverFactory(
|
|
518
|
-
requireContext,
|
|
519
|
-
() => limits.modelSelection,
|
|
520
|
-
() => limits.toolFiltering,
|
|
521
|
-
() => inheritedTools.snapshot(),
|
|
522
|
-
() => limits.subagentExtensions,
|
|
523
|
-
);
|
|
524
|
-
let driverFactory = makeDriverFactory();
|
|
525
|
-
const toolsFor = (path: string) =>
|
|
526
|
-
agentTools(
|
|
527
|
-
requireManager,
|
|
528
|
-
path,
|
|
529
|
-
() => store.list(),
|
|
530
|
-
(type) => driverFactory.resolveAgentSettings(type, path),
|
|
531
|
-
);
|
|
532
|
-
const rootTools = toolsFor("/root");
|
|
533
|
-
let toolsEnabled: boolean | undefined;
|
|
534
|
-
const syncTools = () => {
|
|
535
|
-
const enabled = limits.subagentMode !== "off";
|
|
536
|
-
if (toolsEnabled === enabled) return;
|
|
537
|
-
toolsEnabled = enabled;
|
|
538
|
-
for (const tool of rootTools) {
|
|
539
|
-
pi.registerTool({
|
|
540
|
-
...tool,
|
|
541
|
-
// Hidden tools are neither model-visible nor discoverable/callable via codemode.
|
|
542
|
-
exposure: enabled ? "direct" : "hidden",
|
|
543
|
-
prepareLoadout: inheritedTools.captureLoadout,
|
|
544
|
-
execute: (...args) => {
|
|
545
|
-
if (limits.subagentMode === "off") throw new Error("Subagent Mode is off");
|
|
546
|
-
inheritedTools.captureContext(args[4]);
|
|
547
|
-
return tool.execute(...args);
|
|
548
|
-
},
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
};
|
|
552
|
-
const refreshWidget = (ctx: ExtensionContext) => {
|
|
553
|
-
if (limits.subagentMode === "off") {
|
|
554
|
-
if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
|
|
555
|
-
} else
|
|
556
|
-
updateWidget(
|
|
557
|
-
ctx,
|
|
558
|
-
widgetThreads(),
|
|
559
|
-
widgetCollapsed ? "minimal" : limits.widgetMode,
|
|
560
|
-
limits.nerdFontIcons,
|
|
561
|
-
rootTurnEnded,
|
|
562
|
-
limits.loaderStyle,
|
|
563
|
-
widgetCollapsed && limits.widgetMode === "full",
|
|
564
|
-
);
|
|
565
|
-
};
|
|
566
|
-
pi.on("agent_start", async (_event, ctx) => {
|
|
567
|
-
// A new task must not resurrect the previous task's settled agents. Automatic
|
|
568
|
-
// final-recap turns still belong to that task and keep its results visible.
|
|
569
|
-
if (manager && !rootTurnRunning) {
|
|
570
|
-
for (const thread of manager.list()) {
|
|
571
|
-
if (thread.state !== "starting" && thread.state !== "running")
|
|
572
|
-
hiddenWidgetThreads.add(thread.path);
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
rootTurnEnded = false;
|
|
576
|
-
if (manager) refreshWidget(ctx);
|
|
577
|
-
});
|
|
578
|
-
pi.on("agent_end", async (_event, ctx) => {
|
|
579
|
-
rootTurnEnded = true;
|
|
580
|
-
if (manager) refreshWidget(ctx);
|
|
581
|
-
refreshCostFooter(ctx);
|
|
582
|
-
// A migration can span clarification turns. Reload after each root turn, without converting files.
|
|
583
|
-
if (limits.subagentMode === "off" || !migrationRequested) return;
|
|
584
|
-
store.reload();
|
|
585
|
-
if (store.diagnostics.length) context?.ui.notify(store.diagnostics.join("\n"), "warning");
|
|
586
|
-
});
|
|
587
|
-
|
|
588
|
-
// The footer normally refreshes when subagents report metrics or when a root turn ends.
|
|
589
|
-
// Without any subagents running there are no metric events, so refresh on main-session
|
|
590
|
-
// turn boundaries to keep the ongoing total accurate.
|
|
591
|
-
pi.on("message_end", async (_event, ctx) => {
|
|
592
|
-
refreshCostFooter(ctx);
|
|
593
|
-
});
|
|
594
|
-
pi.on("tool_execution_end", async (_event, ctx) => {
|
|
595
|
-
refreshCostFooter(ctx);
|
|
596
|
-
});
|
|
597
|
-
syncTools();
|
|
598
|
-
pi.on("before_agent_start", async (event, ctx) => {
|
|
599
|
-
// Re-verify on every turn: the Labs opt-in AND live checklist eligibility must both hold.
|
|
600
|
-
const prompt = subagentPrompt(
|
|
601
|
-
limits,
|
|
602
|
-
limits.checklistIntegration &&
|
|
603
|
-
limits.subagentMode !== "off" &&
|
|
604
|
-
currentChecklistStatus(ctx).eligible,
|
|
605
|
-
);
|
|
606
|
-
if (!prompt) return;
|
|
607
|
-
if (
|
|
608
|
-
limits.subagentMode === "opportunistic" &&
|
|
609
|
-
"prompt" in event &&
|
|
610
|
-
event.prompt.startsWith(IMPORT_REQUEST_PREFIX)
|
|
611
|
-
) {
|
|
612
|
-
try {
|
|
613
|
-
markImportOffered(getAgentDir());
|
|
614
|
-
} catch (error) {
|
|
615
|
-
ctx.ui.notify(`Could not save import onboarding state: ${String(error)}`, "warning");
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
return {
|
|
619
|
-
systemPrompt: `${event.systemPrompt}\n\n${prompt}`,
|
|
620
|
-
};
|
|
621
|
-
});
|
|
622
|
-
|
|
623
|
-
const attachSession = async (
|
|
624
|
-
ctx: ExtensionContext,
|
|
625
|
-
installEditor = false,
|
|
626
|
-
seedHistory = true,
|
|
627
|
-
) => {
|
|
628
|
-
cancelSummary();
|
|
629
|
-
housekeeping.cancelAll();
|
|
630
|
-
const token = ++generation;
|
|
631
|
-
closeNavigation(installEditor);
|
|
632
|
-
navigation = new AgentNavigationController(returnToWidget);
|
|
633
|
-
// session_start already belongs to the replacement session: never append the old registry here.
|
|
634
|
-
if (manager) await manager.shutdown();
|
|
635
|
-
inheritedTools.reset();
|
|
636
|
-
// pi-checklist reseeds its own state on these same lifecycle events.
|
|
637
|
-
checklistMirror.reset(ctx);
|
|
638
|
-
context = ctx;
|
|
639
|
-
costLedger = new CostLedger();
|
|
640
|
-
costLedger.restore(ctx.sessionManager.getEntries());
|
|
641
|
-
costFooter.reset(ctx);
|
|
642
|
-
rootTurnEnded = false;
|
|
643
|
-
if (installEditor) {
|
|
644
|
-
widgetCollapsed = false;
|
|
645
|
-
hiddenWidgetThreads.clear();
|
|
646
|
-
}
|
|
647
|
-
store = new ConfigStore({
|
|
648
|
-
cwd: ctx.cwd,
|
|
649
|
-
agentDir: getAgentDir(),
|
|
650
|
-
includeProject: ctx.isProjectTrusted(),
|
|
651
|
-
});
|
|
652
|
-
registryWriter.reset();
|
|
653
|
-
const settingsDiagnostics = loadLimits(ctx);
|
|
654
|
-
syncTools();
|
|
655
|
-
driverFactory = makeDriverFactory();
|
|
656
|
-
const instance = new ThreadManager({
|
|
657
|
-
...limits,
|
|
658
|
-
createDriver: driverFactory,
|
|
659
|
-
rootSnapshot: () => buildSessionContext(requireContext().sessionManager.getBranch()).messages,
|
|
660
|
-
rootContextEntries: () =>
|
|
661
|
-
inheritedContextEntries(requireContext().sessionManager.getBranch()),
|
|
662
|
-
getType: (name) => store.get(name),
|
|
663
|
-
toolsFor,
|
|
664
|
-
onEventError: (error, event) => {
|
|
665
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
666
|
-
context?.ui.notify(`Subagent ${event.kind} notification failed: ${message}`, "warning");
|
|
667
|
-
},
|
|
668
|
-
onActivity: (activity) => {
|
|
669
|
-
if (token === generation) housekeeping.notify(activity);
|
|
670
|
-
},
|
|
671
|
-
onEvent: (event) => {
|
|
672
|
-
if (token !== generation) return;
|
|
673
|
-
// Settled agents and explicit progress reports (which replace the summary) cancel pending
|
|
674
|
-
// housekeeping so an older request cannot reapply stale text; fresh activity reschedules.
|
|
675
|
-
if (
|
|
676
|
-
event.kind === "update" ||
|
|
677
|
-
(event.thread.state !== "starting" && event.thread.state !== "running")
|
|
678
|
-
)
|
|
679
|
-
housekeeping.settle(event.thread.path);
|
|
680
|
-
refreshWidget(requireContext());
|
|
681
|
-
if (event.kind !== "metrics") persist();
|
|
682
|
-
if (event.kind === "settled") rollupCost(event.thread);
|
|
683
|
-
else refreshCostFooter(requireContext());
|
|
684
|
-
delivery(event);
|
|
685
|
-
},
|
|
686
|
-
});
|
|
687
|
-
manager = instance;
|
|
688
|
-
if (installEditor) installNavigationEditor(ctx, seedHistory);
|
|
689
|
-
try {
|
|
690
|
-
const saved = readRegistry(ctx.sessionManager.getBranch());
|
|
691
|
-
// Forked parents own a new registry; they must not share writable child transcripts.
|
|
692
|
-
if (saved?.rootSessionId === ctx.sessionManager.getSessionId())
|
|
693
|
-
instance.restore(saved.threads);
|
|
694
|
-
else if (saved) persist();
|
|
695
|
-
} catch (error) {
|
|
696
|
-
if (limits.subagentMode !== "off")
|
|
697
|
-
ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
|
|
698
|
-
}
|
|
699
|
-
// Recover a persisted settlement whose ledger append was interrupted, including runs paused on reload.
|
|
700
|
-
for (const saved of instance.saved()) rollupCost({ ...saved.view, updatedAt: Date.now() });
|
|
701
|
-
restoreRootMailbox(ctx);
|
|
702
|
-
refreshWidget(ctx);
|
|
703
|
-
const diagnostics = [...store.diagnostics, ...settingsDiagnostics];
|
|
704
|
-
if (limits.subagentMode !== "off" && diagnostics.length)
|
|
705
|
-
ctx.ui.notify(diagnostics.join("\n"), "warning");
|
|
706
|
-
};
|
|
707
|
-
pi.on("session_start", async (event, ctx) => {
|
|
708
|
-
capabilityActive = true;
|
|
709
|
-
await attachSession(ctx, true, event.reason !== "startup");
|
|
710
|
-
if (limits.subagentMode !== "off") await importAgents(ctx, true);
|
|
711
|
-
});
|
|
712
|
-
pi.on("session_tree", async (_event, ctx) => attachSession(ctx));
|
|
713
|
-
const stopWorkingThreads = async () => {
|
|
714
|
-
cancelSummary();
|
|
715
|
-
closeNavigation();
|
|
716
|
-
suspendingSummaries = true;
|
|
717
|
-
try {
|
|
718
|
-
if (!manager) return;
|
|
719
|
-
for (const thread of manager.list()) {
|
|
720
|
-
const state = manager.get(thread.path).state;
|
|
721
|
-
if (state === "starting" || state === "running") await manager.stop("/root", thread.path);
|
|
722
|
-
}
|
|
723
|
-
} finally {
|
|
724
|
-
cancelSummary();
|
|
725
|
-
suspendingSummaries = false;
|
|
726
|
-
}
|
|
727
|
-
};
|
|
728
|
-
// Finish old-thread cancellation while appendEntry still points to the old branch/session.
|
|
729
|
-
pi.on("session_before_tree", stopWorkingThreads);
|
|
730
|
-
pi.on("session_before_switch", stopWorkingThreads);
|
|
731
|
-
pi.on("session_before_fork", stopWorkingThreads);
|
|
732
|
-
pi.on("session_shutdown", async () => {
|
|
733
|
-
capabilityActive = false;
|
|
734
|
-
cancelSummary();
|
|
735
|
-
housekeeping.cancelAll();
|
|
736
|
-
generation++;
|
|
737
|
-
closeNavigation(true);
|
|
738
|
-
await manager?.shutdown();
|
|
739
|
-
costFooter.clear();
|
|
740
|
-
// A clean close leaves an exact checkpoint for releases that cannot read deltas.
|
|
741
|
-
registryWriter.reset();
|
|
742
|
-
persist();
|
|
743
|
-
if (context?.hasUI) context.ui.setWidget("pi-subagent", undefined);
|
|
744
|
-
manager = undefined;
|
|
745
|
-
context = undefined;
|
|
746
|
-
});
|
|
747
|
-
const agentSubcommands = ["tree", "settings", "types", "import", "reload", "reap"] as const;
|
|
748
|
-
const spawnModes = ["fork", "fresh"] as const;
|
|
749
|
-
/** `/agents fork:<type> <task>` inherits the main conversation; `fresh:` starts with no context. */
|
|
750
|
-
const spawnFromCommand = async (
|
|
751
|
-
ctx: ExtensionContext,
|
|
752
|
-
mode: (typeof spawnModes)[number],
|
|
753
|
-
typeName: string,
|
|
754
|
-
task: string,
|
|
755
|
-
) => {
|
|
756
|
-
if (limits.subagentMode === "off") {
|
|
757
|
-
ctx.ui.notify("Subagent Mode is off. Change it in /agents settings.", "warning");
|
|
758
|
-
return;
|
|
759
|
-
}
|
|
760
|
-
const current = requireManager();
|
|
761
|
-
if (!store.list().some((type) => type.name === typeName)) {
|
|
762
|
-
ctx.ui.notify(`Unknown agent type: ${typeName}`, "error");
|
|
763
|
-
return;
|
|
764
|
-
}
|
|
765
|
-
const base = typeName.replace(/[^A-Za-z0-9_-]/g, "-").replace(/^[^A-Za-z0-9]+/, "") || "agent";
|
|
766
|
-
const taken = new Set(current.list().map((thread) => thread.path));
|
|
767
|
-
const prefix = mode === "fork" ? "/root/" : "/";
|
|
768
|
-
let n = 1;
|
|
769
|
-
while (taken.has(`${prefix}${base}-${n}`)) n++;
|
|
770
|
-
const path = `${prefix}${base}-${n}`;
|
|
771
|
-
try {
|
|
772
|
-
await current.scope("/root").spawn({ path, type: typeName, task, wait: false });
|
|
773
|
-
persist();
|
|
774
|
-
refreshWidget(ctx);
|
|
775
|
-
ctx.ui.notify(
|
|
776
|
-
`Started ${typeName} (${mode === "fork" ? "forked context" : "fresh context"}) at ${path}`,
|
|
777
|
-
"info",
|
|
778
|
-
);
|
|
779
|
-
} catch (error) {
|
|
780
|
-
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
781
|
-
}
|
|
782
|
-
};
|
|
783
|
-
pi.registerCommand("agents", {
|
|
784
|
-
description:
|
|
785
|
-
"Configure agent settings, show the live tree, or run /agents fork:<agent> | fresh:<agent> <task>",
|
|
786
|
-
getArgumentCompletions: (argumentText) => {
|
|
787
|
-
const text = argumentText.trimStart();
|
|
788
|
-
const completed = text.match(/^(\S+)(\s+)([\s\S]*)$/);
|
|
789
|
-
if (completed) {
|
|
790
|
-
const command = completed[1]!.toLowerCase();
|
|
791
|
-
if (command === "tree") {
|
|
792
|
-
const paths = (manager?.list() ?? [])
|
|
793
|
-
.map((thread) => thread.path)
|
|
794
|
-
.filter((path) => path !== "/root");
|
|
795
|
-
const matched = fuzzyFilter(paths, completed[3]!.trimStart(), (path) => path);
|
|
796
|
-
if (matched.length === 0) return null;
|
|
797
|
-
return matched.map((path) => ({
|
|
798
|
-
value: `tree ${path}`,
|
|
799
|
-
label: path,
|
|
800
|
-
}));
|
|
801
|
-
}
|
|
802
|
-
if ((agentSubcommands as readonly string[]).includes(command)) return null;
|
|
803
|
-
if (/^(fork|fresh):/.test(command)) return null;
|
|
804
|
-
}
|
|
805
|
-
const lower = text.toLowerCase();
|
|
806
|
-
const colon = lower.indexOf(":");
|
|
807
|
-
// "fo", "fork", "fork:", "fork:wo" -> every matching `fork:<agent>` / `fresh:<agent>`.
|
|
808
|
-
if (lower === "f")
|
|
809
|
-
return spawnModes.map((mode) => ({ value: `${mode}:`, label: `${mode}:` }));
|
|
810
|
-
const modes = spawnModes.filter((mode) =>
|
|
811
|
-
colon >= 0 ? lower.slice(0, colon) === mode : lower.length >= 2 && mode.startsWith(lower),
|
|
812
|
-
);
|
|
813
|
-
if (modes.length) {
|
|
814
|
-
const names = store.list().map((type) => type.name);
|
|
815
|
-
const filter = colon >= 0 ? lower.slice(colon + 1) : "";
|
|
816
|
-
const matched = filter ? fuzzyFilter(names, filter, (name) => name) : names;
|
|
817
|
-
const out = modes.flatMap((mode) =>
|
|
818
|
-
matched.map((name) => ({
|
|
819
|
-
value: `${mode}:${name}`,
|
|
820
|
-
label: `${mode}:${name}`,
|
|
821
|
-
})),
|
|
822
|
-
);
|
|
823
|
-
if (out.length) return out;
|
|
824
|
-
}
|
|
825
|
-
const matched = fuzzyFilter([...agentSubcommands], text, (name) => name);
|
|
826
|
-
if (matched.length === 0) return null;
|
|
827
|
-
return matched.map((value) => ({ value, label: value }));
|
|
828
|
-
},
|
|
829
|
-
handler: async (args, ctx) => {
|
|
830
|
-
const [command, ...rest] = args.trim().split(/\s+/);
|
|
831
|
-
const spawnMatch = args.trim().match(/^(fork|fresh):(\S+)(?:\s+([\s\S]*))?$/);
|
|
832
|
-
if (spawnMatch) {
|
|
833
|
-
const task = spawnMatch[3]?.trim();
|
|
834
|
-
if (!task)
|
|
835
|
-
ctx.ui.notify(`Usage: /agents ${spawnMatch[1]}:${spawnMatch[2]} <task>`, "warning");
|
|
836
|
-
else await spawnFromCommand(ctx, spawnMatch[1] as "fork" | "fresh", spawnMatch[2]!, task);
|
|
837
|
-
} else if (command === "import") {
|
|
838
|
-
await importAgents(ctx, false);
|
|
839
|
-
} else if (command === "types") {
|
|
840
|
-
await editAgentTypes(ctx, store, limits.nerdFontIcons, {
|
|
841
|
-
getAllTools: () => pi.getAllTools(),
|
|
842
|
-
toolFiltering: limits.toolFiltering,
|
|
843
|
-
resolveAgentSettings: (type) => driverFactory.resolveAgentSettings(type, "/root"),
|
|
844
|
-
});
|
|
845
|
-
store.reload();
|
|
846
|
-
} else if (command === "reload") {
|
|
847
|
-
store.reload();
|
|
848
|
-
const diagnostics = [...store.diagnostics, ...loadLimits(ctx)];
|
|
849
|
-
requireManager().setLimits(limits);
|
|
850
|
-
syncTools();
|
|
851
|
-
refreshWidget(ctx);
|
|
852
|
-
restoreRootMailbox(ctx);
|
|
853
|
-
ctx.ui.notify(
|
|
854
|
-
diagnostics.length
|
|
855
|
-
? diagnostics.join("\n")
|
|
856
|
-
: `Loaded ${store.list().length} agent types; maximum ${limits.maxLevels} levels`,
|
|
857
|
-
diagnostics.length ? "warning" : "info",
|
|
858
|
-
);
|
|
859
|
-
} else if (!command || command === "settings") {
|
|
860
|
-
await configureAgents(ctx, {
|
|
861
|
-
store,
|
|
862
|
-
settings: limits,
|
|
863
|
-
agentDir: getAgentDir(),
|
|
864
|
-
getAllTools: () => pi.getAllTools(),
|
|
865
|
-
checklistStatus: () => currentChecklistStatus(ctx),
|
|
866
|
-
resolveAgentSettings: (type) => driverFactory.resolveAgentSettings(type, "/root"),
|
|
867
|
-
apply: () => {
|
|
868
|
-
const diagnostics = loadLimits(ctx);
|
|
869
|
-
requireManager().setLimits(limits);
|
|
870
|
-
syncTools();
|
|
871
|
-
refreshWidget(ctx);
|
|
872
|
-
restoreRootMailbox(ctx);
|
|
873
|
-
if (diagnostics.length) ctx.ui.notify(diagnostics.join("\n"), "warning");
|
|
874
|
-
},
|
|
875
|
-
});
|
|
876
|
-
} else if (command === "reap") {
|
|
877
|
-
const current = requireManager();
|
|
878
|
-
const candidates = current.reapCandidates();
|
|
879
|
-
if (!candidates.length) {
|
|
880
|
-
ctx.ui.notify("No completed agents eligible for reaping.", "info");
|
|
881
|
-
return;
|
|
882
|
-
}
|
|
883
|
-
if (!canOpenDialog(ctx)) return;
|
|
884
|
-
closeNavigation();
|
|
885
|
-
const warning = `${candidates.length} completed agent${candidates.length === 1 ? "" : "s"} will be reaped.\nYou will not be able to resume them anymore.`;
|
|
886
|
-
const choice = await dialogMenu(
|
|
887
|
-
ctx,
|
|
888
|
-
"Reap completed agents?",
|
|
889
|
-
[
|
|
890
|
-
{ id: "confirm", label: "Confirm", help: warning },
|
|
891
|
-
{ id: "cancel", label: "Cancel", help: warning },
|
|
892
|
-
],
|
|
893
|
-
{ selectedId: "cancel" },
|
|
894
|
-
);
|
|
895
|
-
if (choice !== "confirm" || manager !== current) return;
|
|
896
|
-
const reaped = current.reap(candidates);
|
|
897
|
-
persist();
|
|
898
|
-
refreshWidget(ctx);
|
|
899
|
-
ctx.ui.notify(
|
|
900
|
-
reaped.length
|
|
901
|
-
? `Reaped ${reaped.length} completed agent(s); their sessions can no longer be resumed.`
|
|
902
|
-
: "No completed agents eligible for reaping.",
|
|
903
|
-
"info",
|
|
904
|
-
);
|
|
905
|
-
} else if (command === "tree") {
|
|
906
|
-
await navigation.open(
|
|
907
|
-
ctx,
|
|
908
|
-
requireManager().scope("/root"),
|
|
909
|
-
rest.join(" ") || undefined,
|
|
910
|
-
limits.nerdFontIcons,
|
|
911
|
-
limits.loaderStyle,
|
|
912
|
-
);
|
|
913
|
-
} else
|
|
914
|
-
ctx.ui.notify(
|
|
915
|
-
"Usage: /agents [tree [path] | settings | types | import | reload | reap | fork:<agent> <task> | fresh:<agent> <task>]",
|
|
916
|
-
"warning",
|
|
917
|
-
);
|
|
918
|
-
},
|
|
919
|
-
});
|
|
920
|
-
}
|