pi-subagent-manager 0.21.1 → 0.23.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/README.md +4 -1
- package/docs/custom-agents.md +1 -1
- package/docs/settings.md +62 -11
- package/docs/subagent-extension-limitations.md +30 -0
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/orch/extensions.ts +56 -0
- package/src/orch/manager.ts +2 -2
- package/src/orch/runtime.ts +178 -26
- package/src/prefs/settings.ts +132 -58
- package/src/types.ts +1 -1
- package/src/ui/agent-loader.ts +40 -5
- package/src/ui/cost-footer.ts +3 -3
- package/src/ui/live-agent-view.ts +1 -5
- package/src/ui/model-picker.ts +30 -8
- package/src/ui/settings-ui.ts +98 -26
- package/src/ui/status-ui.ts +0 -1
- package/src/ui/ui.ts +3 -6
package/README.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/pi-subagent-manager)
|
|
4
4
|
[](https://www.npmjs.com/package/pi-subagent-manager)
|
|
5
|
+
[](https://github.com/championswimmer/pi-subagent-manager/stargazers)
|
|
5
6
|
[](https://github.com/championswimmer/pi-subagent-manager/actions/workflows/tests.yml)
|
|
6
7
|
[](https://codecov.io/gh/championswimmer/pi-subagent-manager)
|
|
7
8
|
|
|
@@ -81,7 +82,9 @@ A live **Agents** widget sits above the input box. Choose **Full** (the existing
|
|
|
81
82
|
- **`npm:pi-footer`:** with the default status-key mode, add **Extension Status** through `/footer` and select **`subagent_cost`**. Event mode instead requires a **Pi Event Value** widget with **Widget ID** entered manually and **Raw value only** enabled; event IDs are not listed in the status selector.
|
|
82
83
|
- Values publish at session start and immediately on subagent startup, including `💵 $0.0000`, then after settlement/settings changes. Total cost includes the main session plus settled subagents. The icon picker offers three Nerd Font choices when the labs toggle is on, otherwise three emoji choices. Status modes leave your footer untouched; event mode retains a fallback showing the selected value/icon when no extension provides `/footer`. See [Cost display settings](docs/settings.md#labs-cost-display-costdisplay) and the [pi-footer setup guide with exact snippets](docs/pi-footer.md).
|
|
83
84
|
|
|
84
|
-
Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names (off by default; requires a Nerd Font in your terminal). Loaders appear **before**, never instead of, the role icon. Choose
|
|
85
|
+
Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names (off by default; requires a Nerd Font in your terminal). Loaders appear **before**, never instead of, the role icon. Choose Braille, ASCII (`| / - \`), ASCII Star (`+ x *`), or ASCII Pulse (`= * -`) with Nerd Fonts off; enabling Nerd Fonts also unlocks Circle and Hourglass under **[labs] Loader style**, with previews of every animation frame and each family's completed, paused, failed, and stopped icons. Custom agent types can set an optional `icon` or use **[labs] Icon** in `/agents types`. See [icon setup](docs/settings.md#labs-nerd-font-icons-nerdfonticons).
|
|
86
|
+
|
|
87
|
+
Enable **[labs] Enable subagent extensions** in `/agents settings` to reload configured user and trusted-project extension hooks in each subagent’s separate session. It is off by default and experimental: hooks that assume main-session state can cause bugs or unintended consequences. This is configured-file discovery, **not exact main-session inheritance**; CLI-only, inline, and built-in extensions are not reloaded. See [subagent extension settings](docs/settings.md#labs-enable-subagent-extensions-subagentextensions) and read the [limitations](docs/subagent-extension-limitations.md) before enabling.
|
|
85
88
|
|
|
86
89
|
Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main agent to summarize detached-agent results, keeping the final response in the main thread. It is off by default and suppressed by Subagent Mode Off. **Enabling it may cause extra model turns and uses more tokens and context.** See [Final Recap](docs/settings.md#labs-final-recap-finalrecap).
|
|
87
90
|
|
package/docs/custom-agents.md
CHANGED
|
@@ -143,7 +143,7 @@ In `/agents types`, select **[labs] Icon** and paste the glyph, then save the ag
|
|
|
143
143
|
| Ctrl+S | Save (or apply a multiline field to the draft) |
|
|
144
144
|
| Esc | Discard draft |
|
|
145
145
|
|
|
146
|
-
The model picker lists selected models first, in fallback order. **Enter** toggles a model
|
|
146
|
+
The model picker lists selected models first, in fallback order. **Enter** toggles a model; **w/s** moves a selected model up/down in browse mode. **/** or **Tab** enters search, where typing (including w/s) filters; **Tab** returns to browsing while keeping the filter. Other typed letters also start search. Unselected models are ranked by fuzzy match against `modelSuggestions`, scoped models first.
|
|
147
147
|
|
|
148
148
|
**External editor** opens the whole Markdown definition in `$VISUAL`, `$EDITOR`,
|
|
149
149
|
or `vi` in fork mode. For an overlay, edit its YAML file directly and reload.
|
package/docs/settings.md
CHANGED
|
@@ -21,6 +21,7 @@ All keys are optional. Defaults:
|
|
|
21
21
|
"costValue": "subagents",
|
|
22
22
|
"costIcon": "money",
|
|
23
23
|
"finalRecap": false,
|
|
24
|
+
"subagentExtensions": false,
|
|
24
25
|
"modelSelection": "pick-first-scoped",
|
|
25
26
|
"toolFiltering": "allowed",
|
|
26
27
|
"maxLevels": 3,
|
|
@@ -61,17 +62,28 @@ Minimal mode groups starting agents with running agents and excludes the main co
|
|
|
61
62
|
|
|
62
63
|
## [labs] Nerd Font icons (`nerdFontIcons`)
|
|
63
64
|
|
|
64
|
-
Experimental features are tagged **[labs]** in
|
|
65
|
+
Experimental features are tagged **[labs]** in the selected setting's help. Row labels omit that prefix to leave room for provenance dots. **[labs] Nerd Font icons** is an on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"nerdFontIcons": true` in your settings file. Configure a [Nerd Font](https://www.nerdfonts.com/) in your terminal first; unsupported fonts may show boxes or incorrect glyphs. The extension does not install or detect fonts.
|
|
65
66
|
|
|
66
|
-
When enabled, an agent type’s optional `icon` appears before its readable name in the full widget, thread browsers, live watcher header, and type picker. Starting/running agents show the selected loader **before the original role icon**, never replacing it. Completed, paused, failed, and stopped agents show that loader family's corresponding static state icon before the role icon. Agents without a configured role icon still show their loader/state indicator. The one-line minimal widget uses the same family's indicators for aggregate status counts. Turning the setting off
|
|
67
|
+
When enabled, an agent type’s optional `icon` appears before its readable name in the full widget, thread browsers, live watcher header, and type picker. Starting/running agents show the selected loader **before the original role icon**, never replacing it. Completed, paused, failed, and stopped agents show that loader family's corresponding static state icon before the role icon. Agents without a configured role icon still show their loader/state indicator. The one-line minimal widget uses the same family's indicators for aggregate status counts. Turning the setting off hides role icons without removing configured icons; portable loaders remain visible; RPC output keeps state indicators static. Saved settings apply immediately to newly rendered widgets and dialogs.
|
|
67
68
|
|
|
68
69
|
All six bundled agents have [role-specific icons](default-agents.md#nerd-font-icons). Add or change an icon with **[labs] Icon** in `/agents types`, or the optional `icon` frontmatter field in [your own agent](custom-agents.md#icons-labs). Retained threads keep the icon from their saved agent definition.
|
|
69
70
|
|
|
70
71
|
## [labs] Loader style (`loaderStyle`)
|
|
71
72
|
|
|
72
|
-
Choose
|
|
73
|
+
Choose a loader in `/agents` settings and save with **Ctrl+S**, or set `loaderStyle` in your settings file:
|
|
73
74
|
|
|
74
|
-
|
|
75
|
+
| Style | Setting | Running frames | Requires Nerd Font |
|
|
76
|
+
| --- | --- | --- | --- |
|
|
77
|
+
| Circle | `circle` (saved default) | Circle slices | Yes |
|
|
78
|
+
| Braille | `braille` | ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏ | No (standard Unicode, not ASCII) |
|
|
79
|
+
| Hourglass | `hourglass` | Hourglass stages | Yes |
|
|
80
|
+
| ASCII | `ascii` | `\| / - \\` | No |
|
|
81
|
+
| ASCII Star | `ascii-star` | `+ x *` | No |
|
|
82
|
+
| ASCII Pulse | `ascii-pulse` | `= * -` | No |
|
|
83
|
+
|
|
84
|
+
With **[labs] Nerd Font icons** off, the picker shows only Braille and ASCII palettes. With it on, all palettes are available. Saved Circle/Hourglass preferences render as ASCII while Nerd Fonts are off, without changing the saved preference. ASCII palettes use `+`, `=`, `!`, and `#` for completed, paused, failed, and stopped states. The compact ASCII animations are inspired by [cli-spinners](https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json) (`line`, `star2`, and `toggle13`).
|
|
85
|
+
|
|
86
|
+
The Labs preview shows every family's running animation frames and completed, paused, failed, and stopped icons, so you can compare all states before choosing. Starting uses the running animation. State indicators precede the role icon when role icons are enabled; the selected family also applies to the minimal widget's counts. In non-animated output, active agents use the family's first frame.
|
|
75
87
|
|
|
76
88
|
## [labs] Cost display (`costDisplay`)
|
|
77
89
|
|
|
@@ -89,6 +101,16 @@ Both status modes use the same public Pi status API: third-party footers may als
|
|
|
89
101
|
|
|
90
102
|
See [Subagent dollar totals in pi-footer](pi-footer.md) for step-by-step setup and copy-paste widget configuration, status-key, and event snippets.
|
|
91
103
|
|
|
104
|
+
## [labs] Enable subagent extensions (`subagentExtensions`)
|
|
105
|
+
|
|
106
|
+
Experimental on/off toggle, **off by default**. Enable **[labs] Enable subagent extensions** in `/agents settings` and save, or set `"subagentExtensions": true`.
|
|
107
|
+
|
|
108
|
+
When a subagent session opens, it reloads enabled extension files from user configuration and, only when the main project is trusted, project configuration. Pi package resource filters and disabled-extension settings are respected; missing packages are skipped, never installed. This manager is excluded to avoid starting a second subagent manager inside each child. Each factory receives a child-local runtime and its hooks run against that child's session. Reloaded extension tools take precedence over inherited main-session bridges, including tools registered on `session_start`; tool filtering still applies. Other inherited tools keep their existing bridges.
|
|
109
|
+
|
|
110
|
+
**This is configured-file discovery, not exact main-session inheritance. Bugs and unintended consequences are possible.** Read [subagent extension limitations](subagent-extension-limitations.md) before enabling it: the guide covers excluded extensions, configuration drift, `input` hook bypasses, shared side effects, non-interactive UI, and main-session tool bridges.
|
|
111
|
+
|
|
112
|
+
Save and apply affects newly opened sessions, including retained sessions reopened after reload. Already-open agents keep their extension runtime until disposed. The main agent's extensions and tool set are not changed. Leave this off unless your extensions are safe to run across separate sessions.
|
|
113
|
+
|
|
92
114
|
## [labs] Final Recap (`finalRecap`)
|
|
93
115
|
|
|
94
116
|
**[labs] Final Recap** is an experimental on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"finalRecap": true` in your settings file.
|
|
@@ -129,7 +151,7 @@ How the type's `tools.allow` / `tools.block` lists are applied.
|
|
|
129
151
|
|
|
130
152
|
- "All" includes child-local built-in and manager tools plus the main session's registered non-hidden tools. Exact-name allow/block lists apply to this inventory.
|
|
131
153
|
- Inherited tools retain exposure and active status. Deferred/codemode tools are discoverable through child-local codemode when permitted; direct tools remain model-facing when active.
|
|
132
|
-
-
|
|
154
|
+
- By default, built-in tools, manager controls, codemode and tool search remain child-local. External calls reuse main-session resources/context rather than loading fresh extensions or MCP connections. With [Enable subagent extensions](#labs-enable-subagent-extensions-subagentextensions), reloaded extension tools execute in the child instead. Bridged callable tools remain subject to the main session's tool policy; session-mutating external tools are not necessarily isolated to the child. Skills and project context files are not automatically loaded.
|
|
133
155
|
- Other custom **model-only** tools fail closed: the SDK cannot bridge them while preserving root permission/result hooks. Run those in the main session.
|
|
134
156
|
- UI/command-driven resumes after reopening the main session need a main-session `agent_*` tool call to establish the execution bridge; use `agent_steer` rather than the thread dialog.
|
|
135
157
|
- Applies to newly started sessions (including retained ones reopened after reload). Already-open sessions keep their selected tools, and the main session's tool set is unchanged.
|
|
@@ -162,9 +184,38 @@ Lower it to keep the tree tidy. Raise it for long sessions with many agents. Whe
|
|
|
162
184
|
|
|
163
185
|
## Scope
|
|
164
186
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
187
|
+
Settings are read in order: **built-in defaults → Global → trusted Current Project**.
|
|
188
|
+
All keys are optional. The dialog saves only values different from the lower layer,
|
|
189
|
+
so unchanged settings continue inheriting future global changes. Restoring defaults
|
|
190
|
+
is a draft edit; in Project scope it can explicitly override non-default global values.
|
|
191
|
+
|
|
192
|
+
Colored dots before each setting describe saved changes: an **accent dot** means
|
|
193
|
+
changed in Global relative to defaults; a **warning dot** means changed in Current
|
|
194
|
+
Project relative to effective global settings. Both dots appear when both layers
|
|
195
|
+
change that setting, even when the project restores the built-in default. Equal
|
|
196
|
+
values are not changes. Unsaved edits do not change the dots. Footer display groups
|
|
197
|
+
the provenance of its three settings; its submenu shows each separately.
|
|
198
|
+
|
|
199
|
+
The save scope is **Global** when no project settings file exists and **Current
|
|
200
|
+
Project** when one exists. It is determined independently for each project; the old
|
|
201
|
+
cross-project `ui-state.json` preference is no longer used by this dialog.
|
|
202
|
+
Untrusted projects always read and save Global only.
|
|
203
|
+
|
|
204
|
+
Changing scope opens a confirmation screen with **Cancel selected by default**:
|
|
205
|
+
|
|
206
|
+
- **Global → Current Project:** Confirm creates the project settings file as an
|
|
207
|
+
empty object (inheriting global). Unsaved edits are kept; Save and apply writes
|
|
208
|
+
them to Project. Future edits in this project use Project scope.
|
|
209
|
+
- **Current Project → Global:** Confirm deletes only this manager's project
|
|
210
|
+
settings file, discards unsaved edits, reloads global/default values immediately,
|
|
211
|
+
and routes future saves to Global. Project values are not copied into Global.
|
|
212
|
+
- **Cancel / Esc:** no files, values, or scope are changed.
|
|
213
|
+
|
|
214
|
+
Confirmed scope changes happen **immediately** and survive cancelling the outer
|
|
215
|
+
settings screen. Ordinary value edits still require **Save and apply**. Running
|
|
216
|
+
agents and retained threads are kept.
|
|
217
|
+
|
|
218
|
+
The dialog warns about invalid settings layers. Project saves are blocked until an
|
|
219
|
+
invalid Global layer is fixed, rather than persisting a default-based snapshot.
|
|
220
|
+
If settings layers change while the dialog is open, Save and scope transitions
|
|
221
|
+
refuse the stale draft: reopen settings to load the new values before editing.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Subagent extension limitations
|
|
2
|
+
|
|
3
|
+
**[labs] Enable subagent extensions** (`subagentExtensions`) is experimental and **off by default**. It reloads configured extension files into separate subagent sessions. Bugs and unintended consequences are possible; enable it only when your extensions are safe to run in multiple sessions.
|
|
4
|
+
|
|
5
|
+
See [the setting and how to enable it](settings.md#labs-enable-subagent-extensions-subagentextensions).
|
|
6
|
+
|
|
7
|
+
## Not an exact copy of the main agent's extensions
|
|
8
|
+
|
|
9
|
+
- The public Pi extension API does not expose the main session's loaded-extension inventory. Subagents discover enabled extension files from user configuration and, only when the main project is trusted, project configuration.
|
|
10
|
+
- **CLI-only, inline, and built-in extensions are not reloaded.** Configured file extensions are supported; this manager is excluded to avoid starting another subagent manager inside each child.
|
|
11
|
+
- Configuration changed since the main session loaded can produce a different extension set in a newly opened subagent session. Disabled-extension settings and package resource filters are respected. Missing packages are skipped, never installed.
|
|
12
|
+
- Saving the toggle affects newly opened sessions, including retained sessions reopened after reload. Already-open agents keep their extension runtime until disposed; the main agent's runtime is unchanged.
|
|
13
|
+
|
|
14
|
+
## Some messages bypass `input` hooks
|
|
15
|
+
|
|
16
|
+
Initial prompts run `input` hooks. **Durable steering and replayed queued mailbox messages bypass `input` hooks** to preserve mailbox delivery semantics. Request-time context hooks still run, but an extension cannot rely on its `input` handler seeing or transforming every subagent message.
|
|
17
|
+
|
|
18
|
+
## Separate sessions do not isolate every side effect
|
|
19
|
+
|
|
20
|
+
Each reloaded factory receives a child-local runtime, and its hooks operate on that child's session rather than the main session. Hooks that assume main-session state may behave incorrectly. Sessions can run concurrently, so writes to shared files, external services, or other shared state can conflict or produce repeated side effects.
|
|
21
|
+
|
|
22
|
+
Subagents use **non-interactive print mode**, not the main agent's interactive terminal UI. Extensions that require dialogs, confirmations, or other interactive UI may not work as expected. Session shutdown hooks are awaited before child contexts are invalidated, but extensions must still handle their own session-scoped resources safely.
|
|
23
|
+
|
|
24
|
+
## Some tools still execute through the main session
|
|
25
|
+
|
|
26
|
+
Reloaded extension tools take precedence over inherited main-session bridges, including tools registered on `session_start`; agent tool filtering still applies. Tools that are not reloaded, including built-in MCP tools, retain the existing main-session bridge.
|
|
27
|
+
|
|
28
|
+
**Bridged calls run through both child hooks and the main session's hooks.** They reuse main-session resources and context, so session-mutating tools are not necessarily isolated to the child, and hook side effects can occur in both sessions. Built-in codemode and tool search remain child-local rather than reusing the main agent's implementations.
|
|
29
|
+
|
|
30
|
+
Leave the setting off if your extensions require exact main-session inheritance, interactive UI, or an `input` hook for every delivered message.
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -452,6 +452,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
452
452
|
() => limits.modelSelection,
|
|
453
453
|
() => limits.toolFiltering,
|
|
454
454
|
() => inheritedTools.snapshot(),
|
|
455
|
+
() => limits.subagentExtensions,
|
|
455
456
|
);
|
|
456
457
|
let driverFactory = makeDriverFactory();
|
|
457
458
|
const toolsFor = (path: string) =>
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { realpath, readFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { DefaultPackageManager, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
|
|
6
|
+
const MANAGER_ENTRY = fileURLToPath(new URL("../index.ts", import.meta.url));
|
|
7
|
+
|
|
8
|
+
async function canonical(file: string): Promise<string> {
|
|
9
|
+
return realpath(file).catch(() => path.resolve(file));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Exclude this manager before executing factories, including installed copies and symlinks. */
|
|
13
|
+
async function isManagerExtension(file: string, packageRoot?: string): Promise<boolean> {
|
|
14
|
+
const resolved = await canonical(file);
|
|
15
|
+
if (resolved === (await canonical(MANAGER_ENTRY))) return true;
|
|
16
|
+
// Explicit paths and auto-discovered symlinks may not have package metadata.
|
|
17
|
+
let directory = packageRoot ?? path.dirname(resolved);
|
|
18
|
+
while (true) {
|
|
19
|
+
try {
|
|
20
|
+
const manifest = JSON.parse(await readFile(path.join(directory, "package.json"), "utf8"));
|
|
21
|
+
return manifest.name === "pi-subagent-manager";
|
|
22
|
+
} catch {
|
|
23
|
+
const parent = path.dirname(directory);
|
|
24
|
+
if (parent === directory) return false;
|
|
25
|
+
directory = parent;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The public ExtensionAPI cannot inspect the main session's resource loader. This is
|
|
32
|
+
* deliberately configured-file discovery, not exact main-set inheritance: CLI-only,
|
|
33
|
+
* inline and built-in extensions are not reloaded. Missing packages are never installed.
|
|
34
|
+
*/
|
|
35
|
+
export async function discoverSubagentExtensions(options: {
|
|
36
|
+
cwd: string;
|
|
37
|
+
agentDir: string;
|
|
38
|
+
projectTrusted: boolean;
|
|
39
|
+
}): Promise<string[]> {
|
|
40
|
+
const settingsManager = SettingsManager.create(options.cwd, options.agentDir, {
|
|
41
|
+
projectTrusted: options.projectTrusted,
|
|
42
|
+
});
|
|
43
|
+
const packages = new DefaultPackageManager({ ...options, settingsManager });
|
|
44
|
+
const resources = await packages.resolve(async () => "skip");
|
|
45
|
+
const paths: string[] = [];
|
|
46
|
+
const seen = new Set<string>();
|
|
47
|
+
for (const resource of resources.extensions) {
|
|
48
|
+
if (!resource.enabled || resource.path.startsWith("builtin:")) continue;
|
|
49
|
+
if (await isManagerExtension(resource.path, resource.metadata.packageRoot)) continue;
|
|
50
|
+
const resolved = await canonical(resource.path);
|
|
51
|
+
if (seen.has(resolved)) continue;
|
|
52
|
+
seen.add(resolved);
|
|
53
|
+
paths.push(resource.path);
|
|
54
|
+
}
|
|
55
|
+
return paths;
|
|
56
|
+
}
|
package/src/orch/manager.ts
CHANGED
|
@@ -617,7 +617,7 @@ export class ThreadManager {
|
|
|
617
617
|
await record.driver?.abort();
|
|
618
618
|
await record.initializing?.catch(() => {});
|
|
619
619
|
await record.run;
|
|
620
|
-
record.driver?.dispose();
|
|
620
|
+
await record.driver?.dispose();
|
|
621
621
|
}),
|
|
622
622
|
);
|
|
623
623
|
}
|
|
@@ -745,7 +745,7 @@ export class ThreadManager {
|
|
|
745
745
|
.then(async (driver) => {
|
|
746
746
|
if (this.disposed || signal.aborted) {
|
|
747
747
|
await driver.abort();
|
|
748
|
-
driver.dispose();
|
|
748
|
+
await driver.dispose();
|
|
749
749
|
throw new Error("Driver startup cancelled");
|
|
750
750
|
}
|
|
751
751
|
record.driver = driver;
|
package/src/orch/runtime.ts
CHANGED
|
@@ -5,6 +5,10 @@ import { existsSync } from "node:fs";
|
|
|
5
5
|
import { mkdir, readFile, realpath } from "node:fs/promises";
|
|
6
6
|
import {
|
|
7
7
|
createAgentSession,
|
|
8
|
+
createExtensionRuntime,
|
|
9
|
+
ExtensionRunner,
|
|
10
|
+
ModelRegistry,
|
|
11
|
+
createSyntheticSourceInfo,
|
|
8
12
|
createCodemodeExtension,
|
|
9
13
|
createToolSearchExtension,
|
|
10
14
|
DefaultResourceLoader,
|
|
@@ -23,6 +27,7 @@ import {
|
|
|
23
27
|
} from "./mailbox.ts";
|
|
24
28
|
import { selectTools } from "../prefs/config.ts";
|
|
25
29
|
import { TranscriptChannel } from "./transcript.ts";
|
|
30
|
+
import { discoverSubagentExtensions } from "./extensions.ts";
|
|
26
31
|
import type { InheritedToolSource } from "./inherited-tools.ts";
|
|
27
32
|
import type { ModelSelectionMode, ToolFilteringMode } from "../prefs/settings.ts";
|
|
28
33
|
import {
|
|
@@ -143,12 +148,13 @@ async function assertAcceptedSessionFile(
|
|
|
143
148
|
}
|
|
144
149
|
}
|
|
145
150
|
|
|
146
|
-
/** Isolated SDK sessions
|
|
151
|
+
/** Isolated SDK sessions; configured extension reload is experimental and opt-in. */
|
|
147
152
|
export function createDriverFactory(
|
|
148
153
|
getRootContext: () => ExtensionContext,
|
|
149
154
|
getModelSelection: () => ModelSelectionMode = () => "pick-first-scoped",
|
|
150
155
|
getToolFiltering: () => ToolFilteringMode = () => "allowed",
|
|
151
156
|
getInheritedTools: () => InheritedToolSource = () => ({ tools: [], activeNames: [] }),
|
|
157
|
+
getSubagentExtensions: () => boolean = () => false,
|
|
152
158
|
): DriverFactory & {
|
|
153
159
|
resolveAgentSettings(type: AgentType, parentPath: string): ResolvedAgentSettings;
|
|
154
160
|
} {
|
|
@@ -246,6 +252,7 @@ export function createDriverFactory(
|
|
|
246
252
|
const ctx = getRootContext();
|
|
247
253
|
// Tool policy is a startup snapshot; retained live sessions keep their selected set.
|
|
248
254
|
const toolFiltering = getToolFiltering();
|
|
255
|
+
const subagentExtensions = getSubagentExtensions();
|
|
249
256
|
const rootId = ctx.sessionManager.getSessionId();
|
|
250
257
|
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(rootId))
|
|
251
258
|
throw new Error("Unsafe root session id for subagent storage");
|
|
@@ -393,10 +400,14 @@ export function createDriverFactory(
|
|
|
393
400
|
rootActive.has(name) ||
|
|
394
401
|
(options.type.tools?.allow?.includes(name) && toolFiltering === "allowed"),
|
|
395
402
|
);
|
|
396
|
-
const
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
403
|
+
const projectTrusted = ctx.isProjectTrusted?.() ?? false;
|
|
404
|
+
const extensionPaths = subagentExtensions
|
|
405
|
+
? await discoverSubagentExtensions({ cwd: ctx.cwd, agentDir, projectTrusted })
|
|
406
|
+
: [];
|
|
407
|
+
// Keep discovery settings OUT of this loader: reload() resolves packages with
|
|
408
|
+
// auto-install enabled. An empty in-memory package/resource list ensures it
|
|
409
|
+
// only loads the already-resolved files and cannot install missing packages.
|
|
410
|
+
const settingsManager = SettingsManager.inMemory({ cacheWarming: "off" }, { projectTrusted });
|
|
400
411
|
let parkQueue = () => {};
|
|
401
412
|
const pauseBoundary = () => {
|
|
402
413
|
if (!options.shouldPause()) return undefined;
|
|
@@ -408,6 +419,38 @@ export function createDriverFactory(
|
|
|
408
419
|
agentDir,
|
|
409
420
|
settingsManager,
|
|
410
421
|
noExtensions: true,
|
|
422
|
+
additionalExtensionPaths: extensionPaths,
|
|
423
|
+
// Put bridges AFTER file extensions in the runner registry. First registration
|
|
424
|
+
// wins there, including tools registered by file extensions on session_start
|
|
425
|
+
// or later. SDK customTools would always override those child-local tools.
|
|
426
|
+
extensionsOverride: subagentExtensions
|
|
427
|
+
? (base) => {
|
|
428
|
+
const sourceInfo = createSyntheticSourceInfo("<subagent-inherited-tools>", {
|
|
429
|
+
source: "sdk",
|
|
430
|
+
});
|
|
431
|
+
base.extensions.push({
|
|
432
|
+
path: "<subagent-inherited-tools>",
|
|
433
|
+
resolvedPath: "<subagent-inherited-tools>",
|
|
434
|
+
sourceInfo,
|
|
435
|
+
handlers: new Map(),
|
|
436
|
+
tools: new Map(
|
|
437
|
+
externalTools
|
|
438
|
+
.filter(
|
|
439
|
+
(tool) =>
|
|
440
|
+
allowed.has(tool.name) &&
|
|
441
|
+
tool.name !== "codemode" &&
|
|
442
|
+
tool.name !== "tool_search",
|
|
443
|
+
)
|
|
444
|
+
.map((definition) => [definition.name, { definition, sourceInfo }]),
|
|
445
|
+
),
|
|
446
|
+
messageRenderers: new Map(),
|
|
447
|
+
commands: new Map(),
|
|
448
|
+
flags: new Map(),
|
|
449
|
+
shortcuts: new Map(),
|
|
450
|
+
});
|
|
451
|
+
return base;
|
|
452
|
+
}
|
|
453
|
+
: undefined,
|
|
411
454
|
noSkills: true,
|
|
412
455
|
noPromptTemplates: true,
|
|
413
456
|
noContextFiles: true,
|
|
@@ -430,8 +473,24 @@ export function createDriverFactory(
|
|
|
430
473
|
extensionFactories: [
|
|
431
474
|
// These orchestrators must see the CHILD loadout. Forwarding root codemode would
|
|
432
475
|
// let scripts discover/call tools outside the child's allow/block policy.
|
|
433
|
-
...(allowed.has("codemode")
|
|
434
|
-
|
|
476
|
+
...(allowed.has("codemode")
|
|
477
|
+
? [
|
|
478
|
+
subagentExtensions
|
|
479
|
+
? { name: "child-codemode", factory: createCodemodeExtension(), replaceable: true }
|
|
480
|
+
: createCodemodeExtension(),
|
|
481
|
+
]
|
|
482
|
+
: []),
|
|
483
|
+
...(allowed.has("tool_search")
|
|
484
|
+
? [
|
|
485
|
+
subagentExtensions
|
|
486
|
+
? {
|
|
487
|
+
name: "child-tool-search",
|
|
488
|
+
factory: createToolSearchExtension(),
|
|
489
|
+
replaceable: true,
|
|
490
|
+
}
|
|
491
|
+
: createToolSearchExtension(),
|
|
492
|
+
]
|
|
493
|
+
: []),
|
|
435
494
|
(pi) => {
|
|
436
495
|
pi.on("turn_end", pauseBoundary);
|
|
437
496
|
pi.on("agent_before_settle", pauseBoundary);
|
|
@@ -445,22 +504,104 @@ export function createDriverFactory(
|
|
|
445
504
|
});
|
|
446
505
|
options.signal.throwIfAborted();
|
|
447
506
|
await loader.reload();
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
507
|
+
const loadedExtensions = loader.getExtensions();
|
|
508
|
+
// Manager controls remain SDK custom tools so loaded extensions cannot replace
|
|
509
|
+
// them. With reload disabled, preserve the existing SDK bridge behavior exactly.
|
|
510
|
+
const customTools = [...options.tools, ...(subagentExtensions ? [] : externalTools)].filter(
|
|
511
|
+
(tool) => allowed.has(tool.name) && tool.name !== "codemode" && tool.name !== "tool_search",
|
|
512
|
+
);
|
|
513
|
+
let session: Awaited<ReturnType<typeof createAgentSession>>["session"];
|
|
514
|
+
try {
|
|
515
|
+
({ session } = await createAgentSession({
|
|
516
|
+
cwd: ctx.cwd,
|
|
517
|
+
agentDir,
|
|
518
|
+
modelRuntime: runtime,
|
|
519
|
+
model,
|
|
520
|
+
thinkingLevel,
|
|
521
|
+
scopedModels: [...initialScopedModels],
|
|
522
|
+
settingsManager,
|
|
523
|
+
resourceLoader: loader,
|
|
524
|
+
sessionManager,
|
|
525
|
+
// SDK `tools` is both a registry allowlist and an initial active list.
|
|
526
|
+
// Register every permitted deferred tool, then narrow declarations after bind.
|
|
527
|
+
tools: toolNames,
|
|
528
|
+
customTools,
|
|
529
|
+
}));
|
|
530
|
+
} catch (error) {
|
|
531
|
+
if (subagentExtensions) {
|
|
532
|
+
// No session was returned, so normal disposal is unavailable. Give loaded
|
|
533
|
+
// factories a shutdown-only runner with child-local metadata/persistence;
|
|
534
|
+
// unavailable session actions remain throwing stubs, not root bridges.
|
|
535
|
+
await (async () => {
|
|
536
|
+
const runner = new ExtensionRunner(
|
|
537
|
+
loadedExtensions.extensions,
|
|
538
|
+
loadedExtensions.runtime,
|
|
539
|
+
ctx.cwd,
|
|
540
|
+
sessionManager,
|
|
541
|
+
new ModelRegistry(runtime),
|
|
542
|
+
);
|
|
543
|
+
try {
|
|
544
|
+
runner.bindCore(
|
|
545
|
+
{
|
|
546
|
+
...createExtensionRuntime(),
|
|
547
|
+
appendEntry: (customType, data) =>
|
|
548
|
+
sessionManager.appendCustomEntry(customType, data),
|
|
549
|
+
getSessionName: () => sessionManager.getSessionName(),
|
|
550
|
+
getSettings: () => settingsManager.getSettings(),
|
|
551
|
+
getThinkingLevel: () => clampThinkingLevel(model, thinkingLevel),
|
|
552
|
+
},
|
|
553
|
+
{
|
|
554
|
+
getModel: () => model,
|
|
555
|
+
getScopedModels: () => initialScopedModels,
|
|
556
|
+
isIdle: () => true,
|
|
557
|
+
isProjectTrusted: () => projectTrusted,
|
|
558
|
+
getSignal: () => undefined,
|
|
559
|
+
abort: () => {},
|
|
560
|
+
hasPendingMessages: () => false,
|
|
561
|
+
shutdown: () => {},
|
|
562
|
+
getContextUsage: () => undefined,
|
|
563
|
+
compact: () => {},
|
|
564
|
+
getSystemPrompt: () => loader.getSystemPrompt() ?? "",
|
|
565
|
+
},
|
|
566
|
+
);
|
|
567
|
+
await runner.emit({ type: "session_shutdown", reason: "quit" });
|
|
568
|
+
} finally {
|
|
569
|
+
runner.invalidate();
|
|
570
|
+
}
|
|
571
|
+
})().catch(() => {
|
|
572
|
+
// Best-effort cleanup must not hide the SDK's original startup failure.
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
throw error;
|
|
576
|
+
}
|
|
577
|
+
const unsubscribeExtensionErrors = subagentExtensions
|
|
578
|
+
? session.extensionRunner.onError((error) =>
|
|
579
|
+
options.onEvent({
|
|
580
|
+
kind: "error",
|
|
581
|
+
text: `Extension ${error.extensionPath} (${error.event}): ${error.error}`.slice(
|
|
582
|
+
0,
|
|
583
|
+
1000,
|
|
584
|
+
),
|
|
585
|
+
}),
|
|
586
|
+
)
|
|
587
|
+
: () => {};
|
|
588
|
+
let shutdownPromise: Promise<void> | undefined;
|
|
589
|
+
const disposeSession = () => {
|
|
590
|
+
if (!subagentExtensions) {
|
|
591
|
+
session.dispose();
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
// SDK dispose invalidates contexts but does not emit session_shutdown. Await
|
|
595
|
+
// handlers before invalidation so session-scoped resources can be released.
|
|
596
|
+
return (shutdownPromise ??= (async () => {
|
|
597
|
+
try {
|
|
598
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
599
|
+
} finally {
|
|
600
|
+
unsubscribeExtensionErrors();
|
|
601
|
+
session.dispose();
|
|
602
|
+
}
|
|
603
|
+
})());
|
|
604
|
+
};
|
|
464
605
|
let lastScopedModelsKey = "";
|
|
465
606
|
const updateResolved = () => {
|
|
466
607
|
const currentModel = session.model;
|
|
@@ -530,13 +671,24 @@ export function createDriverFactory(
|
|
|
530
671
|
updateResolved();
|
|
531
672
|
};
|
|
532
673
|
try {
|
|
674
|
+
// Factories have already run: abort/load failures must use the same awaited
|
|
675
|
+
// shutdown lifecycle as failures during extension binding, without emitting
|
|
676
|
+
// session_start or starting a model turn.
|
|
677
|
+
options.signal.throwIfAborted();
|
|
678
|
+
if (subagentExtensions && loadedExtensions.errors.length) {
|
|
679
|
+
throw new Error(
|
|
680
|
+
`Subagent extension loading failed: ${loadedExtensions.errors
|
|
681
|
+
.map(({ path, error }) => `${path}: ${error}`)
|
|
682
|
+
.join("; ")}`,
|
|
683
|
+
);
|
|
684
|
+
}
|
|
533
685
|
await enforceScopedModelPolicy();
|
|
534
686
|
options.signal.throwIfAborted();
|
|
535
687
|
await session.bindExtensions({ mode: "print" });
|
|
536
688
|
session.setActiveToolsByName(activeToolNames);
|
|
537
689
|
options.signal.throwIfAborted();
|
|
538
690
|
} catch (error) {
|
|
539
|
-
|
|
691
|
+
await disposeSession();
|
|
540
692
|
throw error;
|
|
541
693
|
}
|
|
542
694
|
const streamFunction = session.agent.streamFunction;
|
|
@@ -766,13 +918,13 @@ export function createDriverFactory(
|
|
|
766
918
|
await abortPromise;
|
|
767
919
|
},
|
|
768
920
|
dispose() {
|
|
769
|
-
if (disposed) return;
|
|
921
|
+
if (disposed) return shutdownPromise;
|
|
770
922
|
disposed = true;
|
|
771
923
|
aborted = true;
|
|
772
924
|
restoreAppends();
|
|
773
925
|
transcript.dispose();
|
|
774
926
|
unsubscribe();
|
|
775
|
-
|
|
927
|
+
return disposeSession();
|
|
776
928
|
},
|
|
777
929
|
async sendUpdate(content) {
|
|
778
930
|
assertOpen();
|