@xzzpig/pi-subagents 0.4.1 → 0.4.2
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 +7 -0
- package/docs/agents.md +1 -1
- package/docs/extension-api.md +20 -0
- package/package.json +2 -1
- package/src/agents/agent-management.ts +318 -25
- package/src/api/agent-management.ts +9 -0
- package/src/api/preflight.ts +8 -4
- package/src/runs/foreground/execution.ts +96 -69
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.4.2] - 2026-08-20
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- Normalize native `message_end` tool-result events into the foreground progress snapshot, alongside `tool_result_end`, with `toolCallId` de-duplication. This keeps bounded tool-result records available to structured delegation consumers across Pi host event shapes.
|
|
10
|
+
- Verify an ejected agent's copied skills and launch tool plan before reporting success; failed verification removes only the file created by that eject attempt.
|
|
11
|
+
|
|
5
12
|
## [0.4.0] - 2026-08-16
|
|
6
13
|
|
|
7
14
|
### Changed
|
package/docs/agents.md
CHANGED
|
@@ -86,7 +86,7 @@ Disable and restore:
|
|
|
86
86
|
- `disabled: true` hides a builtin from runtime discovery and agent-facing `subagent({ action: "list" })` output.
|
|
87
87
|
- `subagents.disableBuiltins: true` disables all builtins at once.
|
|
88
88
|
- `subagent({ action: "disable", agent: "reviewer" })` writes the override without editing settings by hand; `subagent({ action: "enable", agent: "reviewer" })` removes it.
|
|
89
|
-
- `subagent({ action: "eject", agent: "reviewer" })` copies a bundled builtin or package agent
|
|
89
|
+
- `subagent({ action: "eject", agent: "reviewer" })` copies a bundled builtin or package agent into the user or project agent dir (default `user`) as an editable custom file that shadows the original. Relative resource paths are normalized to stable paths; ejection validates copied skills and launch tool configuration, and removes only the new file when that validation fails.
|
|
90
90
|
- `subagent({ action: "reset", agent: "reviewer" })` deletes the scope's custom agent file and/or settings override entry, restoring the bundled default. It refuses if no bundled default exists (use `delete` for purely custom agents).
|
|
91
91
|
|
|
92
92
|
`eject`, `disable`, `enable`, and `reset` accept `agentScope: "user" | "project"` and operate in one scope at a time. Project overrides still win over user ones, so a project-scope disable survives a user-scope `enable` until you target the project scope.
|
package/docs/extension-api.md
CHANGED
|
@@ -133,6 +133,26 @@ Boundaries:
|
|
|
133
133
|
- It is side-effect-free for launch state: it does not create child sessions, temp prompt files, structured-output runtimes, tool-diagnostic files, or run artifacts.
|
|
134
134
|
- Some host-owned facts, such as exact fork snapshots, nested async roots, and live model registries, can only be proven by the Pi host; those appear as `host_required` diagnostics instead of silently pretending to be exact.
|
|
135
135
|
|
|
136
|
+
## Agent ejection API
|
|
137
|
+
|
|
138
|
+
Use `@xzzpig/pi-subagents/agent-management` when an extension needs to make a bundled agent editable without parsing model-facing management output:
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
import { ejectAgentDefinition } from "@xzzpig/pi-subagents/agent-management";
|
|
142
|
+
|
|
143
|
+
const result = ejectAgentDefinition({
|
|
144
|
+
cwd: ctx.cwd,
|
|
145
|
+
agent: "reviewer",
|
|
146
|
+
scope: "project",
|
|
147
|
+
projectTrusted: ctx.isProjectTrusted(),
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
if (!result.ok) throw new Error(result.message);
|
|
151
|
+
console.log(result.targetPath, result.verification.launchPreflighted);
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
The operation never overwrites an existing agent, chain, or conflicting file. Package-relative tool, extension, and skill paths are normalized before writing. After rediscovery, it validates copied skills and the static child launch tool plan; if that check fails, it removes only the new file created by that call and returns `preflight_failed`. Host-dependent checks such as the live model registry and actual child process startup remain the responsibility of the caller's normal launch preflight/execution path.
|
|
155
|
+
|
|
136
156
|
## Structured delegation API
|
|
137
157
|
|
|
138
158
|
Other Pi extensions can ask `pi-subagents` to run one configured foreground leaf agent through the structured delegation API. It uses the established `prompt-template:subagent:*` event family and the same executor as the `subagent` tool; it does not add another launcher.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xzzpig/pi-subagents",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
|
|
5
5
|
"author": "Nico Bailon",
|
|
6
6
|
"license": "MIT",
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
"./delegation": "./src/api/delegation.ts",
|
|
13
13
|
"./capability-ceiling": "./src/api/capability-ceiling.ts",
|
|
14
14
|
"./preflight": "./src/api/preflight.ts",
|
|
15
|
+
"./agent-management": "./src/api/agent-management.ts",
|
|
15
16
|
"./control-channel": "./src/api/control-channel.ts",
|
|
16
17
|
"./intercom-bridge": "./src/api/intercom-bridge.ts",
|
|
17
18
|
"./pi-args": "./src/api/pi-args.ts",
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
defaultInheritProjectContext,
|
|
13
13
|
defaultInheritSkills,
|
|
14
14
|
defaultSystemPromptMode,
|
|
15
|
+
discoverAgents,
|
|
15
16
|
discoverAgentsAll,
|
|
16
17
|
buildRuntimeName,
|
|
17
18
|
frontmatterNameForConfig,
|
|
@@ -24,11 +25,12 @@ import {
|
|
|
24
25
|
import { serializeAgent } from "./agent-serializer.ts";
|
|
25
26
|
import { mergeAgentsForScope } from "./agent-selection.ts";
|
|
26
27
|
import { serializeChain, serializeJsonChain } from "./chain-serializer.ts";
|
|
27
|
-
import { discoverAvailableSkills, resolveSkills } from "./skills.ts";
|
|
28
|
+
import { discoverAvailableSkills, resolveSkills, resolveSkillsWithFallback } from "./skills.ts";
|
|
28
29
|
import {
|
|
29
30
|
buildProactiveSkillSubagentRecommendationLines,
|
|
30
31
|
} from "./proactive-skills.ts";
|
|
31
32
|
import { parseFrontmatter } from "./frontmatter.ts";
|
|
33
|
+
import { resolvePiLaunchToolPlan } from "../runs/shared/pi-args.ts";
|
|
32
34
|
import { toModelInfo } from "../shared/model-info.ts";
|
|
33
35
|
import { resolveSubagentModelOverride, type ParentModel } from "../runs/shared/model-fallback.ts";
|
|
34
36
|
import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
|
|
@@ -38,6 +40,60 @@ import type { AcceptanceInput, Details, ExtensionConfig, ToolBudgetConfig } from
|
|
|
38
40
|
import { getProjectConfigDir } from "../shared/utils.ts";
|
|
39
41
|
import { capabilityCeilingAgentRestrictionSources, isAgentAllowedByCapabilityCeiling, resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
|
|
40
42
|
|
|
43
|
+
export const AGENT_MANAGEMENT_API_VERSION = 1 as const;
|
|
44
|
+
|
|
45
|
+
export type AgentEjectionScope = "user" | "project";
|
|
46
|
+
|
|
47
|
+
export type AgentEjectionErrorCode =
|
|
48
|
+
| "invalid_agent"
|
|
49
|
+
| "untrusted_project"
|
|
50
|
+
| "missing_project_root"
|
|
51
|
+
| "missing_source"
|
|
52
|
+
| "existing_custom"
|
|
53
|
+
| "name_conflict"
|
|
54
|
+
| "existing_file"
|
|
55
|
+
| "source_read_failed"
|
|
56
|
+
| "resource_missing"
|
|
57
|
+
| "write_failed"
|
|
58
|
+
| "rediscovery_failed"
|
|
59
|
+
| "preflight_failed";
|
|
60
|
+
|
|
61
|
+
export interface EjectAgentDefinitionInput {
|
|
62
|
+
cwd: string;
|
|
63
|
+
agent: string;
|
|
64
|
+
scope: AgentEjectionScope;
|
|
65
|
+
/** Direct project-scope API callers must affirm host project trust. */
|
|
66
|
+
projectTrusted?: boolean;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface EjectAgentDefinitionVerification {
|
|
70
|
+
agent: string;
|
|
71
|
+
scope: AgentEjectionScope;
|
|
72
|
+
targetPath: string;
|
|
73
|
+
source: "builtin" | "package";
|
|
74
|
+
resourcePaths: string[];
|
|
75
|
+
launchPreflighted: true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type EjectAgentDefinitionResult =
|
|
79
|
+
| {
|
|
80
|
+
ok: true;
|
|
81
|
+
code: "ejected";
|
|
82
|
+
message: string;
|
|
83
|
+
agent: string;
|
|
84
|
+
source: "builtin" | "package";
|
|
85
|
+
scope: AgentEjectionScope;
|
|
86
|
+
targetPath: string;
|
|
87
|
+
verification: EjectAgentDefinitionVerification;
|
|
88
|
+
}
|
|
89
|
+
| {
|
|
90
|
+
ok: false;
|
|
91
|
+
code: AgentEjectionErrorCode;
|
|
92
|
+
message: string;
|
|
93
|
+
scope?: AgentEjectionScope;
|
|
94
|
+
targetPath?: string;
|
|
95
|
+
};
|
|
96
|
+
|
|
41
97
|
type ManagementAction = "list" | "get" | "models" | "create" | "update" | "delete" | "eject" | "disable" | "enable" | "reset";
|
|
42
98
|
type ManagementScope = "user" | "project";
|
|
43
99
|
type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string };
|
|
@@ -1108,42 +1164,279 @@ function handleDelete(params: ManagementParams, ctx: ManagementContext): AgentTo
|
|
|
1108
1164
|
return result(`Deleted chain '${target.name}' at ${target.filePath}.`);
|
|
1109
1165
|
}
|
|
1110
1166
|
|
|
1111
|
-
function
|
|
1112
|
-
|
|
1113
|
-
|
|
1167
|
+
function isRelativeAgentResourcePath(value: string): boolean {
|
|
1168
|
+
return value === "." || value === ".." || value.startsWith("./") || value.startsWith("../");
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
function resolvePortableAgentResources(
|
|
1172
|
+
entries: string[] | undefined,
|
|
1173
|
+
sourceFilePath: string,
|
|
1174
|
+
): { entries: string[] | undefined; resourcePaths: string[] } {
|
|
1175
|
+
const baseDir = path.dirname(sourceFilePath);
|
|
1176
|
+
const resourcePaths = (entries ?? [])
|
|
1177
|
+
.filter(isRelativeAgentResourcePath)
|
|
1178
|
+
.map((entry) => path.resolve(baseDir, entry));
|
|
1179
|
+
return {
|
|
1180
|
+
entries: entries?.map((entry) => isRelativeAgentResourcePath(entry) ? path.resolve(baseDir, entry) : entry),
|
|
1181
|
+
resourcePaths,
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
function portableEjectedAgentContent(source: AgentConfig): {
|
|
1186
|
+
content?: string;
|
|
1187
|
+
resourcePaths?: string[];
|
|
1188
|
+
error?: EjectAgentDefinitionResult;
|
|
1189
|
+
} {
|
|
1190
|
+
let sourceContent: string;
|
|
1191
|
+
try {
|
|
1192
|
+
sourceContent = fs.readFileSync(source.filePath, "utf-8");
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1195
|
+
return {
|
|
1196
|
+
error: {
|
|
1197
|
+
ok: false,
|
|
1198
|
+
code: "source_read_failed",
|
|
1199
|
+
message: `Failed to read source agent at ${source.filePath}: ${message}`,
|
|
1200
|
+
},
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
const extensions = resolvePortableAgentResources(source.extensions, source.filePath);
|
|
1205
|
+
const subagentOnlyExtensions = resolvePortableAgentResources(source.subagentOnlyExtensions, source.filePath);
|
|
1206
|
+
const skillPath = resolvePortableAgentResources(source.skillPath, source.filePath);
|
|
1207
|
+
const tools = resolvePortableAgentResources(source.tools, source.filePath);
|
|
1208
|
+
const resourcePaths = [...new Set([
|
|
1209
|
+
...extensions.resourcePaths,
|
|
1210
|
+
...subagentOnlyExtensions.resourcePaths,
|
|
1211
|
+
...skillPath.resourcePaths,
|
|
1212
|
+
...tools.resourcePaths,
|
|
1213
|
+
])].sort((a, b) => a.localeCompare(b));
|
|
1214
|
+
const missingResources = resourcePaths.filter((resourcePath) => !fs.existsSync(resourcePath));
|
|
1215
|
+
if (missingResources.length > 0) {
|
|
1216
|
+
return {
|
|
1217
|
+
error: {
|
|
1218
|
+
ok: false,
|
|
1219
|
+
code: "resource_missing",
|
|
1220
|
+
message: `Agent '${source.name}' cannot be ejected because its relative resource path(s) do not exist: ${missingResources.join(", ")}.`,
|
|
1221
|
+
},
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
1224
|
+
if (resourcePaths.length === 0) return { content: sourceContent, resourcePaths };
|
|
1225
|
+
|
|
1226
|
+
const { frontmatter } = parseFrontmatter(sourceContent);
|
|
1227
|
+
const portableAgent: AgentConfig = {
|
|
1228
|
+
...source,
|
|
1229
|
+
...(source.extensions !== undefined ? { extensions: extensions.entries! } : {}),
|
|
1230
|
+
...(source.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: subagentOnlyExtensions.entries! } : {}),
|
|
1231
|
+
...(source.skillPath !== undefined ? { skillPath: skillPath.entries! } : {}),
|
|
1232
|
+
...(source.tools !== undefined ? { tools: tools.entries! } : {}),
|
|
1233
|
+
};
|
|
1234
|
+
return {
|
|
1235
|
+
content: serializeAgent(portableAgent, { preserveFrontmatterFields: new Set(Object.keys(frontmatter)) }),
|
|
1236
|
+
resourcePaths,
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
function cleanupEjectedFile(targetPath: string, expectedContent: string): void {
|
|
1241
|
+
try {
|
|
1242
|
+
if (fs.readFileSync(targetPath, "utf-8") === expectedContent) fs.unlinkSync(targetPath);
|
|
1243
|
+
} catch {
|
|
1244
|
+
// The service only cleans the file it created during this call.
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
function validateEjectedAgentLaunchPreflight(agent: AgentConfig, cwd: string): string | undefined {
|
|
1249
|
+
const resolvedSkills = resolveSkillsWithFallback(
|
|
1250
|
+
agent.skills ?? [],
|
|
1251
|
+
cwd,
|
|
1252
|
+
undefined,
|
|
1253
|
+
agent.skillPath,
|
|
1254
|
+
agent.filePath ? path.dirname(agent.filePath) : cwd,
|
|
1255
|
+
);
|
|
1256
|
+
if (resolvedSkills.missing.length > 0) {
|
|
1257
|
+
return `Missing skills: ${resolvedSkills.missing.join(", ")}`;
|
|
1258
|
+
}
|
|
1259
|
+
try {
|
|
1260
|
+
resolvePiLaunchToolPlan({
|
|
1261
|
+
tools: agent.tools,
|
|
1262
|
+
extensions: agent.extensions,
|
|
1263
|
+
subagentOnlyExtensions: agent.subagentOnlyExtensions,
|
|
1264
|
+
mcpDirectTools: agent.mcpDirectTools,
|
|
1265
|
+
cwd,
|
|
1266
|
+
requireReadTool: resolvedSkills.resolved.length > 0,
|
|
1267
|
+
agentName: agent.name,
|
|
1268
|
+
});
|
|
1269
|
+
} catch (error) {
|
|
1270
|
+
return error instanceof Error ? error.message : String(error);
|
|
1271
|
+
}
|
|
1272
|
+
return undefined;
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
/**
|
|
1276
|
+
* Shared extraction of the existing eject handler. It deliberately owns only
|
|
1277
|
+
* agent-definition copying, no-overwrite checks, project-trust input, and
|
|
1278
|
+
* portable package-relative resource paths.
|
|
1279
|
+
*/
|
|
1280
|
+
export function ejectAgentDefinition(input: EjectAgentDefinitionInput): EjectAgentDefinitionResult {
|
|
1281
|
+
const raw = input.agent.trim();
|
|
1114
1282
|
const sanitized = sanitizeName(raw);
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
const scope = parsedScope.scope!;
|
|
1118
|
-
const d = discoverAgentsAll(ctx.cwd);
|
|
1119
|
-
const source = [...d.package, ...d.builtin].find((a) => a.name === raw || a.name === sanitized);
|
|
1120
|
-
if (!source) {
|
|
1121
|
-
return result(`Agent '${raw}' not found or is not a bundled/package agent. eject copies a builtin or package agent to ${scope} scope so it can be customized. Available: ${availableNames(ctx.cwd, "agent").join(", ") || "none"}.`, true);
|
|
1283
|
+
if (!raw || !sanitized) {
|
|
1284
|
+
return { ok: false, code: "invalid_agent", message: "agent must be a non-empty valid agent name." };
|
|
1122
1285
|
}
|
|
1123
|
-
|
|
1124
|
-
|
|
1286
|
+
if (input.scope !== "user" && input.scope !== "project") {
|
|
1287
|
+
return { ok: false, code: "invalid_agent", message: "scope must be 'user' or 'project'." };
|
|
1288
|
+
}
|
|
1289
|
+
if (input.scope === "project" && input.projectTrusted !== true) {
|
|
1290
|
+
return {
|
|
1291
|
+
ok: false,
|
|
1292
|
+
code: "untrusted_project",
|
|
1293
|
+
scope: input.scope,
|
|
1294
|
+
message: "Project scope ejection requires a trusted project. Trust the project and retry.",
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
let discovered: ReturnType<typeof discoverAgentsAll>;
|
|
1299
|
+
try {
|
|
1300
|
+
discovered = discoverAgentsAll(input.cwd);
|
|
1301
|
+
} catch (error) {
|
|
1302
|
+
return {
|
|
1303
|
+
ok: false,
|
|
1304
|
+
code: "rediscovery_failed",
|
|
1305
|
+
scope: input.scope,
|
|
1306
|
+
message: `Unable to discover agents before ejecting: ${error instanceof Error ? error.message : String(error)}`,
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
if (input.scope === "project" && discovered.projectDir === null) {
|
|
1310
|
+
return {
|
|
1311
|
+
ok: false,
|
|
1312
|
+
code: "missing_project_root",
|
|
1313
|
+
scope: input.scope,
|
|
1314
|
+
message: "Project scope ejection is not available here: no project config root (.pi or .agents) was found above the cwd.",
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
const existingCustom = (input.scope === "user" ? discovered.user : discovered.project)
|
|
1319
|
+
.find((candidate) => candidate.name === raw || candidate.name === sanitized);
|
|
1125
1320
|
if (existingCustom) {
|
|
1126
|
-
return
|
|
1321
|
+
return {
|
|
1322
|
+
ok: false,
|
|
1323
|
+
code: "existing_custom",
|
|
1324
|
+
scope: input.scope,
|
|
1325
|
+
targetPath: existingCustom.filePath,
|
|
1326
|
+
message: `Agent '${existingCustom.name}' is already a custom ${input.scope} agent at ${existingCustom.filePath}. Edit it with { action: "update", agent: "${existingCustom.name}" } or delete it first.`,
|
|
1327
|
+
};
|
|
1127
1328
|
}
|
|
1128
|
-
|
|
1129
|
-
|
|
1329
|
+
const bundledCandidates = input.scope === "user"
|
|
1330
|
+
? discoverAgents(input.cwd, "user").agents.filter((candidate) => candidate.source === "builtin" || candidate.source === "package")
|
|
1331
|
+
: [...discovered.package, ...discovered.builtin];
|
|
1332
|
+
const source = bundledCandidates.find((candidate) => candidate.name === raw || candidate.name === sanitized);
|
|
1333
|
+
if (!source) {
|
|
1334
|
+
return {
|
|
1335
|
+
ok: false,
|
|
1336
|
+
code: "missing_source",
|
|
1337
|
+
scope: input.scope,
|
|
1338
|
+
message: `Agent '${raw}' not found or is not a bundled/package agent. eject copies a builtin or package agent to ${input.scope} scope so it can be customized. Available: ${availableNames(input.cwd, "agent").join(", ") || "none"}.`,
|
|
1339
|
+
};
|
|
1130
1340
|
}
|
|
1131
|
-
const
|
|
1132
|
-
|
|
1133
|
-
|
|
1341
|
+
const runtimeName = source.name;
|
|
1342
|
+
if (nameExistsInScope(input.cwd, input.scope, runtimeName)) {
|
|
1343
|
+
return {
|
|
1344
|
+
ok: false,
|
|
1345
|
+
code: "name_conflict",
|
|
1346
|
+
scope: input.scope,
|
|
1347
|
+
message: `An agent or chain named '${runtimeName}' already exists in ${input.scope} scope. Remove or rename it first.`,
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
const targetDir = input.scope === "user" ? discovered.userDir : discovered.projectDir!;
|
|
1134
1352
|
const targetPath = path.join(targetDir, `${runtimeName}.md`);
|
|
1135
1353
|
if (fs.existsSync(targetPath)) {
|
|
1136
|
-
return
|
|
1354
|
+
return {
|
|
1355
|
+
ok: false,
|
|
1356
|
+
code: "existing_file",
|
|
1357
|
+
scope: input.scope,
|
|
1358
|
+
targetPath,
|
|
1359
|
+
message: `File already exists at ${targetPath} but is not a valid agent definition. Remove or rename it first.`,
|
|
1360
|
+
};
|
|
1137
1361
|
}
|
|
1138
|
-
|
|
1362
|
+
|
|
1363
|
+
const portable = portableEjectedAgentContent(source);
|
|
1364
|
+
if (portable.error) return { ...portable.error, scope: input.scope, targetPath };
|
|
1365
|
+
const content = portable.content!;
|
|
1139
1366
|
try {
|
|
1140
|
-
|
|
1367
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
1368
|
+
fs.writeFileSync(targetPath, content, { encoding: "utf-8", flag: "wx" });
|
|
1141
1369
|
} catch (error) {
|
|
1142
1370
|
const message = error instanceof Error ? error.message : String(error);
|
|
1143
|
-
return
|
|
1371
|
+
return {
|
|
1372
|
+
ok: false,
|
|
1373
|
+
code: "write_failed",
|
|
1374
|
+
scope: input.scope,
|
|
1375
|
+
targetPath,
|
|
1376
|
+
message: `Failed to write ejected agent '${runtimeName}' at ${targetPath}: ${message}`,
|
|
1377
|
+
};
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
const rediscovered = discoverAgentsAll(input.cwd);
|
|
1381
|
+
const copied = (input.scope === "user" ? rediscovered.user : rediscovered.project)
|
|
1382
|
+
.find((candidate) => candidate.name === runtimeName && path.resolve(candidate.filePath) === path.resolve(targetPath));
|
|
1383
|
+
if (!copied) {
|
|
1384
|
+
cleanupEjectedFile(targetPath, content);
|
|
1385
|
+
return {
|
|
1386
|
+
ok: false,
|
|
1387
|
+
code: "rediscovery_failed",
|
|
1388
|
+
scope: input.scope,
|
|
1389
|
+
targetPath,
|
|
1390
|
+
message: `Ejected agent '${runtimeName}' could not be rediscovered at ${targetPath}; no file was kept.`,
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
const preflightError = validateEjectedAgentLaunchPreflight(copied, input.cwd);
|
|
1395
|
+
if (preflightError) {
|
|
1396
|
+
cleanupEjectedFile(targetPath, content);
|
|
1397
|
+
return {
|
|
1398
|
+
ok: false,
|
|
1399
|
+
code: "preflight_failed",
|
|
1400
|
+
scope: input.scope,
|
|
1401
|
+
targetPath,
|
|
1402
|
+
message: `Ejected agent '${runtimeName}' failed launch preflight at ${targetPath}: ${preflightError}. No file was kept.`,
|
|
1403
|
+
};
|
|
1144
1404
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1405
|
+
|
|
1406
|
+
const sourceKind = source.source as "builtin" | "package";
|
|
1407
|
+
return {
|
|
1408
|
+
ok: true,
|
|
1409
|
+
code: "ejected",
|
|
1410
|
+
message: `Ejected agent '${runtimeName}' from ${sourceKind} to ${input.scope} scope at ${targetPath}. Edit it there to customize; it shadows the bundled ${sourceKind} agent of the same name.`,
|
|
1411
|
+
agent: runtimeName,
|
|
1412
|
+
source: sourceKind,
|
|
1413
|
+
scope: input.scope,
|
|
1414
|
+
targetPath,
|
|
1415
|
+
verification: {
|
|
1416
|
+
agent: copied.name,
|
|
1417
|
+
scope: input.scope,
|
|
1418
|
+
targetPath,
|
|
1419
|
+
source: sourceKind,
|
|
1420
|
+
resourcePaths: portable.resourcePaths ?? [],
|
|
1421
|
+
launchPreflighted: true,
|
|
1422
|
+
},
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
function handleEject(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
1427
|
+
if (!params.agent) return result("Specify 'agent' for eject.", true);
|
|
1428
|
+
const parsedScope = actionScope(params.agentScope, "eject");
|
|
1429
|
+
if (parsedScope.error) return parsedScope.error;
|
|
1430
|
+
const scope = parsedScope.scope!;
|
|
1431
|
+
const ejected = ejectAgentDefinition({
|
|
1432
|
+
cwd: ctx.cwd,
|
|
1433
|
+
agent: params.agent,
|
|
1434
|
+
scope,
|
|
1435
|
+
// Preserve the existing management-action behavior. Direct public callers
|
|
1436
|
+
// must supply affirmative project trust themselves.
|
|
1437
|
+
...(scope === "project" ? { projectTrusted: true } : {}),
|
|
1438
|
+
});
|
|
1439
|
+
return result(ejected.message, !ejected.ok);
|
|
1147
1440
|
}
|
|
1148
1441
|
|
|
1149
1442
|
function handleDisable(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export {
|
|
2
|
+
AGENT_MANAGEMENT_API_VERSION,
|
|
3
|
+
ejectAgentDefinition,
|
|
4
|
+
type AgentEjectionErrorCode,
|
|
5
|
+
type AgentEjectionScope,
|
|
6
|
+
type EjectAgentDefinitionInput,
|
|
7
|
+
type EjectAgentDefinitionResult,
|
|
8
|
+
type EjectAgentDefinitionVerification,
|
|
9
|
+
} from "../agents/agent-management.ts";
|
package/src/api/preflight.ts
CHANGED
|
@@ -163,11 +163,15 @@ export type SubagentLaunchContractResult =
|
|
|
163
163
|
|
|
164
164
|
function packageVersion(): string {
|
|
165
165
|
const packagePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json");
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
166
|
+
try {
|
|
167
|
+
const parsed = JSON.parse(fs.readFileSync(packagePath, "utf-8")) as { version?: unknown };
|
|
168
|
+
if (typeof parsed.version !== "string" || !parsed.version.trim()) {
|
|
169
|
+
throw new Error("version must be a non-empty string.");
|
|
170
|
+
}
|
|
171
|
+
return parsed.version;
|
|
172
|
+
} catch (error) {
|
|
173
|
+
throw new Error(`Invalid package version in '${packagePath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
169
174
|
}
|
|
170
|
-
return parsed.version;
|
|
171
175
|
}
|
|
172
176
|
|
|
173
177
|
function stableJson(value: unknown): string {
|
|
@@ -700,6 +700,11 @@ async function runSingleAttempt(
|
|
|
700
700
|
|
|
701
701
|
let activeLongRunningNotified = false;
|
|
702
702
|
let pendingToolResult: { tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined;
|
|
703
|
+
// Pi host versions may represent one tool result as either a dedicated
|
|
704
|
+
// tool_result_end event or a message_end whose message role is toolResult.
|
|
705
|
+
// Remember correlated ids so normalizing both forms cannot duplicate output.
|
|
706
|
+
const handledToolResultIds = new Set<string>();
|
|
707
|
+
const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
|
|
703
708
|
type ActiveToolCall = { key: string; tool: string; args: string; startedAt: number; path?: string };
|
|
704
709
|
let activeToolSequence = 0;
|
|
705
710
|
const activeToolCalls = new Map<string, ActiveToolCall>();
|
|
@@ -919,6 +924,53 @@ async function runSingleAttempt(
|
|
|
919
924
|
emitUpdateSnapshot(output || "(running...)");
|
|
920
925
|
};
|
|
921
926
|
|
|
927
|
+
const toolResultCallId = (message: Message): string | undefined => {
|
|
928
|
+
const value = (message as { toolCallId?: unknown }).toolCallId;
|
|
929
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
930
|
+
};
|
|
931
|
+
|
|
932
|
+
const handleToolResult = (message: Message, now: number): void => {
|
|
933
|
+
const callId = toolResultCallId(message);
|
|
934
|
+
if (callId) {
|
|
935
|
+
if (handledToolResultIds.has(callId)) return;
|
|
936
|
+
if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
|
|
937
|
+
const oldest = handledToolResultIds.values().next().value;
|
|
938
|
+
if (typeof oldest === "string") handledToolResultIds.delete(oldest);
|
|
939
|
+
}
|
|
940
|
+
handledToolResultIds.add(callId);
|
|
941
|
+
}
|
|
942
|
+
result.messages!.push(message);
|
|
943
|
+
const resultText = extractTextFromContent(message.content);
|
|
944
|
+
if (options.toolBudget && pendingToolResult && resultText.includes("Tool budget hard limit reached")) {
|
|
945
|
+
result.toolBudgetBlocked = true;
|
|
946
|
+
result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, pendingToolResult.tool);
|
|
947
|
+
}
|
|
948
|
+
appendRecentOutput(progress, resultText.split("\n").slice(-10));
|
|
949
|
+
const toolSnapshot = pendingToolResult;
|
|
950
|
+
pendingToolResult = undefined;
|
|
951
|
+
if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
|
|
952
|
+
recordMutatingFailure(mutatingFailures, {
|
|
953
|
+
tool: toolSnapshot.tool,
|
|
954
|
+
path: toolSnapshot.path,
|
|
955
|
+
error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
|
|
956
|
+
ts: now,
|
|
957
|
+
}, mutatingFailureWindowMs);
|
|
958
|
+
if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
|
|
959
|
+
emitNeedsAttention(now, {
|
|
960
|
+
message: `${agent.name} needs attention after repeated mutating tool failures`,
|
|
961
|
+
reason: "tool_failures",
|
|
962
|
+
currentTool: toolSnapshot.tool,
|
|
963
|
+
currentPath: toolSnapshot.path,
|
|
964
|
+
currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
|
|
965
|
+
recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
} else if (toolSnapshot?.mutates) {
|
|
969
|
+
resetMutatingFailureState(mutatingFailures);
|
|
970
|
+
}
|
|
971
|
+
fireUpdate();
|
|
972
|
+
};
|
|
973
|
+
|
|
922
974
|
const rawStdoutTail = createBoundedByteTail();
|
|
923
975
|
const processLine = (line: string) => {
|
|
924
976
|
if (!line.trim()) return;
|
|
@@ -1003,80 +1055,55 @@ async function runSingleAttempt(
|
|
|
1003
1055
|
}
|
|
1004
1056
|
|
|
1005
1057
|
if (evt.type === "message_end" && evt.message) {
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
result.usage.
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1058
|
+
if (evt.message.role === "toolResult") {
|
|
1059
|
+
handleToolResult(evt.message, now);
|
|
1060
|
+
} else {
|
|
1061
|
+
result.messages!.push(evt.message);
|
|
1062
|
+
if (evt.message.role === "assistant") {
|
|
1063
|
+
result.usage.turns++;
|
|
1064
|
+
progress.turnCount = result.usage.turns;
|
|
1065
|
+
const stopReason = (evt.message as { stopReason?: string }).stopReason;
|
|
1066
|
+
const toolCalls = Array.isArray(evt.message.content)
|
|
1067
|
+
? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
|
|
1068
|
+
: [];
|
|
1069
|
+
const hasToolCall = toolCalls.length > 0;
|
|
1070
|
+
const terminalAssistantStop = stopReason === "stop" && !hasToolCall;
|
|
1071
|
+
const terminalStructuredOutputCall = Boolean(options.structuredOutput)
|
|
1072
|
+
&& toolCalls.length === 1
|
|
1073
|
+
&& (toolCalls[0] as { name?: string }).name === "structured_output";
|
|
1074
|
+
updateTurnBudget(result.usage.turns, terminalAssistantStop || terminalStructuredOutputCall, hasToolCall || Boolean(progress.currentTool));
|
|
1075
|
+
const u = evt.message.usage;
|
|
1076
|
+
if (u) {
|
|
1077
|
+
result.usage.input += u.input || 0;
|
|
1078
|
+
result.usage.output += u.output || 0;
|
|
1079
|
+
result.usage.cacheRead += u.cacheRead || 0;
|
|
1080
|
+
result.usage.cacheWrite += u.cacheWrite || 0;
|
|
1081
|
+
result.usage.cost += u.cost?.total || 0;
|
|
1082
|
+
progress.tokens = result.usage.input + result.usage.output;
|
|
1083
|
+
progress.inputTokens = result.usage.input;
|
|
1084
|
+
progress.outputTokens = result.usage.output;
|
|
1085
|
+
}
|
|
1086
|
+
if (evt.message.model) {
|
|
1087
|
+
progress.model = evt.message.model;
|
|
1088
|
+
if (!result.model) result.model = evt.message.model;
|
|
1089
|
+
}
|
|
1090
|
+
if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
|
|
1091
|
+
const assistantText = extractTextFromContent(evt.message.content);
|
|
1092
|
+
appendRecentOutput(progress, assistantText.split("\n").slice(-10));
|
|
1093
|
+
// Final assistant message: start the exit drain window.
|
|
1094
|
+
if (terminalAssistantStop) {
|
|
1095
|
+
if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
|
|
1096
|
+
cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
|
|
1097
|
+
applyChildLifecycle(projectChildLifecycle(evt, true));
|
|
1098
|
+
}
|
|
1043
1099
|
}
|
|
1100
|
+
updateActivityState(now);
|
|
1101
|
+
fireUpdate();
|
|
1044
1102
|
}
|
|
1045
|
-
updateActivityState(now);
|
|
1046
|
-
fireUpdate();
|
|
1047
1103
|
}
|
|
1048
1104
|
|
|
1049
1105
|
if (evt.type === "tool_result_end" && evt.message) {
|
|
1050
|
-
|
|
1051
|
-
const resultText = extractTextFromContent(evt.message.content);
|
|
1052
|
-
if (options.toolBudget && pendingToolResult && resultText.includes("Tool budget hard limit reached")) {
|
|
1053
|
-
result.toolBudgetBlocked = true;
|
|
1054
|
-
result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, pendingToolResult.tool);
|
|
1055
|
-
}
|
|
1056
|
-
appendRecentOutput(progress, resultText.split("\n").slice(-10));
|
|
1057
|
-
const toolSnapshot = pendingToolResult;
|
|
1058
|
-
pendingToolResult = undefined;
|
|
1059
|
-
if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
|
|
1060
|
-
recordMutatingFailure(mutatingFailures, {
|
|
1061
|
-
tool: toolSnapshot.tool,
|
|
1062
|
-
path: toolSnapshot.path,
|
|
1063
|
-
error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
|
|
1064
|
-
ts: now,
|
|
1065
|
-
}, mutatingFailureWindowMs);
|
|
1066
|
-
if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
|
|
1067
|
-
emitNeedsAttention(now, {
|
|
1068
|
-
message: `${agent.name} needs attention after repeated mutating tool failures`,
|
|
1069
|
-
reason: "tool_failures",
|
|
1070
|
-
currentTool: toolSnapshot.tool,
|
|
1071
|
-
currentPath: toolSnapshot.path,
|
|
1072
|
-
currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
|
|
1073
|
-
recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
|
|
1074
|
-
});
|
|
1075
|
-
}
|
|
1076
|
-
} else if (toolSnapshot?.mutates) {
|
|
1077
|
-
resetMutatingFailureState(mutatingFailures);
|
|
1078
|
-
}
|
|
1079
|
-
fireUpdate();
|
|
1106
|
+
handleToolResult(evt.message, now);
|
|
1080
1107
|
}
|
|
1081
1108
|
};
|
|
1082
1109
|
|