@xzzpig/pi-subagents 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +175 -0
- package/README.md +4 -0
- package/agents/oracle.md +3 -1
- package/agents/reviewer.md +1 -0
- package/agents/scout.md +2 -2
- package/agents/worker.md +2 -1
- package/async-retention-discovery-worker.mjs +180 -0
- package/docs/agents.md +41 -3
- package/docs/configuration.md +41 -13
- package/docs/extension-api.md +65 -2
- package/docs/models.md +2 -0
- package/docs/observability.md +41 -5
- package/docs/tool-reference.md +38 -39
- package/docs/workflows.md +173 -3
- package/package.json +14 -10
- package/prompts/council.md +48 -0
- package/skills/council-mode/SKILL.md +230 -0
- package/skills/pi-subagents/SKILL.md +8 -4
- package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
- package/skills/pi-subagents/references/execution-controls.md +40 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
- package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
- package/src/agents/agent-management.ts +471 -377
- package/src/agents/agent-serializer.ts +2 -0
- package/src/agents/agents.ts +186 -44
- package/src/agents/builtin-names.ts +9 -0
- package/src/agents/runtime-agent-registry.ts +418 -0
- package/src/agents/skills.ts +1 -1
- package/src/api/agent-management.ts +9 -0
- package/src/api/agents.ts +7 -0
- package/src/api/external-job-provider.ts +186 -0
- package/src/api/preflight.ts +45 -13
- package/src/api/shared-types.ts +2 -0
- package/src/extension/config.ts +6 -3
- package/src/extension/doctor.ts +4 -6
- package/src/extension/fanout-child.ts +2 -2
- package/src/extension/index.ts +183 -90
- package/src/extension/public-execution.ts +31 -2
- package/src/extension/rpc.ts +41 -1
- package/src/extension/schemas.ts +17 -37
- package/src/extension/tool-description.ts +35 -24
- package/src/inspectors/herdr/actions.ts +2 -2
- package/src/inspectors/herdr/inspector-runner.ts +2 -1
- package/src/inspectors/herdr/project-panes.ts +2 -2
- package/src/intercom/native-supervisor-channel.ts +32 -10
- package/src/missions/lifecycle.ts +6 -1
- package/src/missions/store.ts +4 -9
- package/src/missions/workflow-state.ts +2 -2
- package/src/profiles/profiles.ts +3 -1
- package/src/runs/background/active-run-index.ts +31 -8
- package/src/runs/background/async-execution.ts +70 -41
- package/src/runs/background/async-job-tracker.ts +24 -7
- package/src/runs/background/async-resume.ts +49 -16
- package/src/runs/background/async-retention.ts +886 -0
- package/src/runs/background/async-status-snapshot.ts +14 -5
- package/src/runs/background/async-status.ts +39 -53
- package/src/runs/background/auto-drain.ts +1 -0
- package/src/runs/background/chain-append.ts +3 -33
- package/src/runs/background/completion-dedupe.ts +5 -1
- package/src/runs/background/completion-replay.ts +22 -12
- package/src/runs/background/control-channel.ts +14 -68
- package/src/runs/background/fleet-view.ts +68 -19
- package/src/runs/background/index-segment.ts +59 -0
- package/src/runs/background/inspect-rpc.ts +443 -0
- package/src/runs/background/notify.ts +31 -5
- package/src/runs/background/result-files.ts +158 -90
- package/src/runs/background/result-watcher.ts +124 -20
- package/src/runs/background/resume-guidance.ts +8 -5
- package/src/runs/background/retained-children.ts +13 -3
- package/src/runs/background/run-id-query.ts +7 -0
- package/src/runs/background/run-id-resolver.ts +11 -9
- package/src/runs/background/run-status.ts +27 -18
- package/src/runs/background/scheduled-runs.ts +24 -4
- package/src/runs/background/stale-run-reconciler.ts +6 -3
- package/src/runs/background/steering.ts +11 -1
- package/src/runs/background/subagent-runner.ts +260 -144
- package/src/runs/background/subagent-wait.ts +17 -13
- package/src/runs/background/terminal-run-index.ts +138 -0
- package/src/runs/background/wait-completions.ts +21 -4
- package/src/runs/background/wait-subscriptions.ts +81 -2
- package/src/runs/background/wait-tool.ts +1 -0
- package/src/runs/foreground/async-steering-action.ts +21 -14
- package/src/runs/foreground/execution.ts +104 -71
- package/src/runs/foreground/subagent-executor.ts +816 -1593
- package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
- package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
- package/src/runs/shared/acceptance.ts +48 -5
- package/src/runs/shared/chain-outputs.ts +1 -3
- package/src/runs/shared/external-job-bridge.ts +444 -0
- package/src/runs/shared/external-job-runner.ts +286 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
- package/src/runs/shared/model-exclusions.ts +242 -0
- package/src/runs/shared/model-fallback.ts +153 -40
- package/src/runs/shared/orca-progress-tabs.ts +84 -22
- package/src/runs/shared/parallel-handoff.ts +46 -4
- package/src/runs/shared/parallel-utils.ts +4 -15
- package/src/runs/shared/permissions.ts +5 -1
- package/src/runs/shared/pi-args.ts +8 -1
- package/src/runs/shared/session-lease.ts +0 -6
- package/src/runs/shared/subagent-control.ts +51 -7
- package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
- package/src/runs/shared/workflow-graph.ts +1 -23
- package/src/runs/shared/worktree.ts +14 -2
- package/src/shared/atomic-json.ts +22 -2
- package/src/shared/capacity-resilient-json.ts +102 -0
- package/src/shared/completion-owner.ts +14 -0
- package/src/shared/file-system-retry.ts +49 -1
- package/src/shared/fork-context.ts +59 -1
- package/src/shared/model-info.ts +20 -0
- package/src/shared/prompt-resources.ts +0 -40
- package/src/shared/settings.ts +5 -29
- package/src/shared/types.ts +106 -26
- package/src/shared/utils.ts +8 -0
- package/src/shared/watch-strategy.ts +10 -0
- package/src/slash/slash-bridge.ts +2 -1
- package/src/slash/slash-commands.ts +47 -7
- package/src/slash/slash-live-state.ts +3 -3
- package/src/tui/fleet-status.ts +86 -1
- package/src/tui/fleet.ts +117 -16
- package/src/tui/render.ts +73 -3
- package/src/watchdog/change-signature.ts +1 -1
- package/src/watchdog/lsp-diagnostics.ts +1 -0
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +320 -79
- package/src/workflows/workflow-receipt.ts +140 -0
- package/src/runs/foreground/chain-clarify.ts +0 -1354
- package/src/runs/foreground/chain-execution.ts +0 -1581
|
@@ -4,16 +4,17 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
|
4
4
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import {
|
|
6
6
|
type AgentConfig,
|
|
7
|
+
type AgentDiscoveryDiagnostic,
|
|
7
8
|
type AgentScope,
|
|
8
9
|
type AgentSource,
|
|
9
|
-
type ChainConfig,
|
|
10
|
-
type ChainStepConfig,
|
|
11
10
|
BUILTIN_AGENT_NAMES,
|
|
12
11
|
defaultInheritProjectContext,
|
|
13
12
|
defaultInheritSkills,
|
|
14
13
|
defaultSystemPromptMode,
|
|
14
|
+
discoverAgents,
|
|
15
15
|
discoverAgentsAll,
|
|
16
16
|
buildRuntimeName,
|
|
17
|
+
findBlockingAgentDiagnostic,
|
|
17
18
|
frontmatterNameForConfig,
|
|
18
19
|
parsePackageName,
|
|
19
20
|
mergeBuiltinAgentOverride,
|
|
@@ -23,12 +24,12 @@ import {
|
|
|
23
24
|
} from "./agents.ts";
|
|
24
25
|
import { serializeAgent } from "./agent-serializer.ts";
|
|
25
26
|
import { mergeAgentsForScope } from "./agent-selection.ts";
|
|
26
|
-
import {
|
|
27
|
-
import { discoverAvailableSkills, resolveSkills } from "./skills.ts";
|
|
27
|
+
import { discoverAvailableSkills, resolveSkills, resolveSkillsWithFallback } from "./skills.ts";
|
|
28
28
|
import {
|
|
29
29
|
buildProactiveSkillSubagentRecommendationLines,
|
|
30
30
|
} from "./proactive-skills.ts";
|
|
31
|
-
import { parseFrontmatter } from "./frontmatter.ts";
|
|
31
|
+
import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.ts";
|
|
32
|
+
import { resolvePiLaunchToolPlan } from "../runs/shared/pi-args.ts";
|
|
32
33
|
import { toModelInfo } from "../shared/model-info.ts";
|
|
33
34
|
import { resolveSubagentModelOverride, type ParentModel } from "../runs/shared/model-fallback.ts";
|
|
34
35
|
import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
|
|
@@ -37,15 +38,69 @@ import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
|
|
|
37
38
|
import type { AcceptanceInput, Details, ExtensionConfig, ToolBudgetConfig } from "../shared/types.ts";
|
|
38
39
|
import { getProjectConfigDir } from "../shared/utils.ts";
|
|
39
40
|
import { capabilityCeilingAgentRestrictionSources, isAgentAllowedByCapabilityCeiling, resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
|
|
41
|
+
import { listRuntimeAgentConfigs, mergeRuntimeAgents, type RuntimeAgentOwner } from "./runtime-agent-registry.ts";
|
|
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
|
+
};
|
|
40
96
|
|
|
41
97
|
type ManagementAction = "list" | "get" | "models" | "create" | "update" | "delete" | "eject" | "disable" | "enable" | "reset";
|
|
42
98
|
type ManagementScope = "user" | "project";
|
|
43
|
-
type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string };
|
|
99
|
+
type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner };
|
|
44
100
|
|
|
45
101
|
interface ManagementParams {
|
|
46
102
|
action?: string;
|
|
47
103
|
agent?: string;
|
|
48
|
-
chainName?: string;
|
|
49
104
|
agentScope?: unknown;
|
|
50
105
|
config?: unknown;
|
|
51
106
|
}
|
|
@@ -76,6 +131,14 @@ function hasKey(obj: Record<string, unknown>, key: string): boolean {
|
|
|
76
131
|
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
77
132
|
}
|
|
78
133
|
|
|
134
|
+
function isJsonSerializable(value: unknown): boolean {
|
|
135
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
136
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
137
|
+
if (Array.isArray(value)) return value.every(isJsonSerializable);
|
|
138
|
+
if (value && typeof value === "object") return Object.values(value).every(isJsonSerializable);
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
|
|
79
142
|
function asDisambiguationScope(scope: unknown): ManagementScope | undefined {
|
|
80
143
|
if (scope === "user" || scope === "project") return scope;
|
|
81
144
|
return undefined;
|
|
@@ -105,14 +168,15 @@ function allAgents(d: { builtin: AgentConfig[]; package: AgentConfig[]; user: Ag
|
|
|
105
168
|
return [...d.builtin, ...d.package, ...d.user, ...d.project];
|
|
106
169
|
}
|
|
107
170
|
|
|
108
|
-
function
|
|
109
|
-
|
|
110
|
-
const items = kind === "agent" ? allAgents(d) : d.chains;
|
|
111
|
-
return [...new Set(items.map((x) => x.name))].sort((a, b) => a.localeCompare(b));
|
|
171
|
+
function availableAgentNamesFromDiscovery(d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] }): string[] {
|
|
172
|
+
return [...new Set(allAgents(d).map((agent) => agent.name))].sort((a, b) => a.localeCompare(b));
|
|
112
173
|
}
|
|
113
174
|
|
|
114
|
-
function
|
|
115
|
-
|
|
175
|
+
function availableAgentNames(cwd: string): string[] {
|
|
176
|
+
return availableAgentNamesFromDiscovery(discoverAgentsAll(cwd));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function findAgentsInDiscovery(name: string, d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] }, scope: AgentScope = "both"): AgentConfig[] {
|
|
116
180
|
const raw = name.trim();
|
|
117
181
|
const sanitized = sanitizeName(raw);
|
|
118
182
|
const scoped = mergeAgentsForScope(scope, d.user, d.project, d.builtin, d.package);
|
|
@@ -125,15 +189,17 @@ function findAgents(name: string, cwd: string, scope: AgentScope = "both"): Agen
|
|
|
125
189
|
.sort((a, b) => a.source.localeCompare(b.source));
|
|
126
190
|
}
|
|
127
191
|
|
|
128
|
-
function
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
192
|
+
function findAgents(name: string, cwd: string, scope: AgentScope = "both"): AgentConfig[] {
|
|
193
|
+
return findAgentsInDiscovery(name, discoverAgentsAll(cwd), scope);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function diagnosticsForScope(diagnostics: AgentDiscoveryDiagnostic[] | undefined, scope: AgentScope): AgentDiscoveryDiagnostic[] | undefined {
|
|
197
|
+
if (scope === "both") return diagnostics;
|
|
198
|
+
const excludedSource = scope === "user" ? "project" : "user";
|
|
199
|
+
return diagnostics?.filter((diagnostic) => diagnostic.source !== excludedSource);
|
|
134
200
|
}
|
|
135
201
|
|
|
136
|
-
const AGENT_SOURCE_PRECEDENCE: Record<AgentSource, number> = { builtin: 0, package: 1, user: 2, project: 3 };
|
|
202
|
+
const AGENT_SOURCE_PRECEDENCE: Record<AgentSource, number> = { builtin: 0, package: 1, user: 2, project: 3, runtime: 4 };
|
|
137
203
|
|
|
138
204
|
// Returns the highest-precedence definition for a resolved canonical name (project > user > package > builtin),
|
|
139
205
|
// matching mergeAgentsForScope for "both", including disabled agents so disable/enable can locate hidden targets.
|
|
@@ -156,9 +222,6 @@ function nameExistsInScope(cwd: string, scope: ManagementScope, name: string, ex
|
|
|
156
222
|
for (const a of scope === "user" ? d.user : d.project) {
|
|
157
223
|
if (a.name === name && a.filePath !== excludePath) return true;
|
|
158
224
|
}
|
|
159
|
-
for (const c of d.chains) {
|
|
160
|
-
if (c.source === scope && c.name === name && c.filePath !== excludePath) return true;
|
|
161
|
-
}
|
|
162
225
|
return false;
|
|
163
226
|
}
|
|
164
227
|
|
|
@@ -166,30 +229,6 @@ function isMutableSource(source: AgentSource): source is ManagementScope {
|
|
|
166
229
|
return source === "user" || source === "project";
|
|
167
230
|
}
|
|
168
231
|
|
|
169
|
-
function unknownChainAgents(cwd: string, steps: ChainStepConfig[]): string[] {
|
|
170
|
-
const d = discoverAgentsAll(cwd);
|
|
171
|
-
const agents = allAgents(d);
|
|
172
|
-
return [...new Set(steps.map((s) => s.agent).filter((agentName): agentName is string => typeof agentName === "string" && !resolveAgentName(agentName, agents).agent))]
|
|
173
|
-
.sort((a, b) => a.localeCompare(b));
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
function chainStepWarnings(ctx: ManagementContext, steps: ChainStepConfig[]): string[] {
|
|
177
|
-
const warnings: string[] = [];
|
|
178
|
-
const available = new Set(discoverAvailableSkills(ctx.cwd).map((s) => s.name));
|
|
179
|
-
for (let i = 0; i < steps.length; i++) {
|
|
180
|
-
const s = steps[i]!;
|
|
181
|
-
if (s.model) {
|
|
182
|
-
const found = ctx.modelRegistry.getAvailable().some((m) => `${m.provider}/${m.id}` === s.model || m.id === s.model);
|
|
183
|
-
if (!found) warnings.push(`Warning: step ${i + 1} (${s.agent}): model '${s.model}' is not in the current model registry.`);
|
|
184
|
-
}
|
|
185
|
-
if (Array.isArray(s.skills) && s.skills.length > 0) {
|
|
186
|
-
const missing = s.skills.filter((sk) => !available.has(sk));
|
|
187
|
-
if (missing.length) warnings.push(`Warning: step ${i + 1} (${s.agent}): skills not found: ${missing.join(", ")}.`);
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
return warnings;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
232
|
function modelWarning(ctx: ManagementContext, model: string | undefined): string | undefined {
|
|
194
233
|
if (!model) return undefined;
|
|
195
234
|
const found = ctx.modelRegistry.getAvailable().some((m) => `${m.provider}/${m.id}` === model || m.id === model);
|
|
@@ -214,11 +253,24 @@ function skillsWarning(cwd: string, agent: Pick<AgentConfig, "skills" | "skillPa
|
|
|
214
253
|
return missing.length ? `Warning: skills not found: ${missing.join(", ")}.` : undefined;
|
|
215
254
|
}
|
|
216
255
|
|
|
256
|
+
function withDeclaredExtensionPaths(config: AgentConfig, filePath: string): AgentConfig {
|
|
257
|
+
const { frontmatter } = parseFrontmatter(fs.readFileSync(filePath, "utf-8"));
|
|
258
|
+
const { extensions: _extensions, subagentOnlyExtensions: _subagentOnlyExtensions, ...withoutResolvedExtensions } = config;
|
|
259
|
+
return {
|
|
260
|
+
...withoutResolvedExtensions,
|
|
261
|
+
...(frontmatter.extensions !== undefined ? { extensions: parseFrontmatterList(frontmatter.extensions) } : {}),
|
|
262
|
+
...(frontmatter.subagentOnlyExtensions !== undefined
|
|
263
|
+
? { subagentOnlyExtensions: parseFrontmatterList(frontmatter.subagentOnlyExtensions) }
|
|
264
|
+
: {}),
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
217
268
|
export function editableAgentConfig(agent: AgentConfig): AgentConfig {
|
|
218
269
|
const { extensions: _extensions, ...withoutExtensions } = agent;
|
|
219
270
|
const base = agent.override?.base;
|
|
220
271
|
const {
|
|
221
272
|
override: _override,
|
|
273
|
+
outputMode: _outputMode,
|
|
222
274
|
model: _model,
|
|
223
275
|
fallbackModels: _fallbackModels,
|
|
224
276
|
thinking: _thinking,
|
|
@@ -238,14 +290,15 @@ export function editableAgentConfig(agent: AgentConfig): AgentConfig {
|
|
|
238
290
|
...editable
|
|
239
291
|
} = withoutExtensions;
|
|
240
292
|
if (!base) {
|
|
241
|
-
return {
|
|
293
|
+
return withDeclaredExtensionPaths({
|
|
242
294
|
...withoutExtensions,
|
|
243
295
|
...(agent.extensionsFromDefault ? {} : agent.extensions !== undefined ? { extensions: [...agent.extensions] } : {}),
|
|
244
|
-
};
|
|
296
|
+
}, agent.filePath);
|
|
245
297
|
}
|
|
246
298
|
|
|
247
|
-
return {
|
|
299
|
+
return withDeclaredExtensionPaths({
|
|
248
300
|
...editable,
|
|
301
|
+
...(base.outputMode !== undefined ? { outputMode: base.outputMode } : {}),
|
|
249
302
|
...(base.model !== undefined ? { model: base.model } : {}),
|
|
250
303
|
...(base.fallbackModels !== undefined ? { fallbackModels: [...base.fallbackModels] } : {}),
|
|
251
304
|
...(base.thinking !== undefined ? { thinking: base.thinking } : {}),
|
|
@@ -263,7 +316,7 @@ export function editableAgentConfig(agent: AgentConfig): AgentConfig {
|
|
|
263
316
|
...(base.extensions !== undefined ? { extensions: [...base.extensions] } : {}),
|
|
264
317
|
...(base.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: [...base.subagentOnlyExtensions] } : {}),
|
|
265
318
|
...(base.completionGuard !== undefined ? { completionGuard: base.completionGuard } : {}),
|
|
266
|
-
};
|
|
319
|
+
}, agent.filePath);
|
|
267
320
|
}
|
|
268
321
|
|
|
269
322
|
function readAgentFrontmatterFields(filePath: string): Set<string> {
|
|
@@ -317,6 +370,7 @@ export function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<
|
|
|
317
370
|
if (hasKey(cfg, "acceptance")) changed("acceptance");
|
|
318
371
|
if (hasKey(cfg, "acceptanceRole")) changed("acceptanceRole");
|
|
319
372
|
if (hasKey(cfg, "output")) changed("output");
|
|
373
|
+
if (hasKey(cfg, "outputMode")) changed("outputMode");
|
|
320
374
|
if (hasKey(cfg, "reads")) changed("defaultReads");
|
|
321
375
|
if (hasKey(cfg, "progress")) changed("defaultProgress");
|
|
322
376
|
if (hasKey(cfg, "maxSubagentDepth")) changed("maxSubagentDepth");
|
|
@@ -329,69 +383,6 @@ export function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<
|
|
|
329
383
|
return fields;
|
|
330
384
|
}
|
|
331
385
|
|
|
332
|
-
function parseStepList(raw: unknown): { steps?: ChainStepConfig[]; error?: string } {
|
|
333
|
-
if (!Array.isArray(raw)) return { error: "config.steps must be an array." };
|
|
334
|
-
if (raw.length === 0) return { error: "config.steps must include at least one step." };
|
|
335
|
-
const steps: ChainStepConfig[] = [];
|
|
336
|
-
for (let i = 0; i < raw.length; i++) {
|
|
337
|
-
const item = raw[i];
|
|
338
|
-
if (!item || typeof item !== "object" || Array.isArray(item)) return { error: `config.steps[${i}] must be an object.` };
|
|
339
|
-
const s = item as Record<string, unknown>;
|
|
340
|
-
if (typeof s.agent !== "string" || !s.agent.trim()) return { error: `config.steps[${i}].agent must be a non-empty string.` };
|
|
341
|
-
const step: ChainStepConfig = { agent: s.agent.trim(), task: typeof s.task === "string" ? s.task : "" };
|
|
342
|
-
if (hasKey(s, "phase")) {
|
|
343
|
-
if (typeof s.phase === "string") step.phase = s.phase;
|
|
344
|
-
else return { error: `config.steps[${i}].phase must be a string.` };
|
|
345
|
-
}
|
|
346
|
-
if (hasKey(s, "label")) {
|
|
347
|
-
if (typeof s.label === "string") step.label = s.label;
|
|
348
|
-
else return { error: `config.steps[${i}].label must be a string.` };
|
|
349
|
-
}
|
|
350
|
-
if (hasKey(s, "as")) {
|
|
351
|
-
if (typeof s.as === "string") step.as = s.as;
|
|
352
|
-
else return { error: `config.steps[${i}].as must be a string.` };
|
|
353
|
-
}
|
|
354
|
-
if (hasKey(s, "outputSchema")) {
|
|
355
|
-
if (typeof s.outputSchema === "string") step.outputSchema = s.outputSchema;
|
|
356
|
-
else return { error: `config.steps[${i}].outputSchema must be a schema file path string for saved chains.` };
|
|
357
|
-
}
|
|
358
|
-
if (hasKey(s, "output")) {
|
|
359
|
-
if (s.output === false) step.output = false;
|
|
360
|
-
else if (typeof s.output === "string") step.output = s.output;
|
|
361
|
-
else return { error: `config.steps[${i}].output must be a string or false.` };
|
|
362
|
-
}
|
|
363
|
-
if (hasKey(s, "outputMode")) {
|
|
364
|
-
if (s.outputMode === "inline" || s.outputMode === "file-only") step.outputMode = s.outputMode;
|
|
365
|
-
else return { error: `config.steps[${i}].outputMode must be 'inline' or 'file-only'.` };
|
|
366
|
-
}
|
|
367
|
-
if (hasKey(s, "reads")) {
|
|
368
|
-
if (s.reads === false) step.reads = false;
|
|
369
|
-
else if (Array.isArray(s.reads)) step.reads = s.reads.filter((v): v is string => typeof v === "string").map((v) => v.trim()).filter(Boolean);
|
|
370
|
-
else return { error: `config.steps[${i}].reads must be an array or false.` };
|
|
371
|
-
}
|
|
372
|
-
if (hasKey(s, "model")) {
|
|
373
|
-
if (typeof s.model === "string") step.model = s.model;
|
|
374
|
-
else return { error: `config.steps[${i}].model must be a string.` };
|
|
375
|
-
}
|
|
376
|
-
if (hasKey(s, "skills")) {
|
|
377
|
-
if (s.skills === false) step.skills = false;
|
|
378
|
-
else if (Array.isArray(s.skills)) step.skills = s.skills.filter((v): v is string => typeof v === "string").map((v) => v.trim()).filter(Boolean);
|
|
379
|
-
else return { error: `config.steps[${i}].skills must be an array or false.` };
|
|
380
|
-
}
|
|
381
|
-
if (hasKey(s, "progress")) {
|
|
382
|
-
if (typeof s.progress === "boolean") step.progress = s.progress;
|
|
383
|
-
else return { error: `config.steps[${i}].progress must be a boolean.` };
|
|
384
|
-
}
|
|
385
|
-
if (hasKey(s, "toolBudget")) {
|
|
386
|
-
const validation = validateToolBudgetConfig(s.toolBudget, `config.steps[${i}].toolBudget`);
|
|
387
|
-
if (validation.error) return { error: validation.error };
|
|
388
|
-
if (s.toolBudget !== undefined) step.toolBudget = s.toolBudget as ToolBudgetConfig;
|
|
389
|
-
}
|
|
390
|
-
steps.push(step);
|
|
391
|
-
}
|
|
392
|
-
return { steps };
|
|
393
|
-
}
|
|
394
|
-
|
|
395
386
|
function parseTools(raw: string): { tools?: string[]; mcpDirectTools?: string[] } {
|
|
396
387
|
const tools: string[] = [];
|
|
397
388
|
const mcpDirectTools: string[] = [];
|
|
@@ -436,7 +427,11 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
|
|
|
436
427
|
&& Object.keys(runner).every((key) => ["type", "command", "args", "promptDelivery"].includes(key))) {
|
|
437
428
|
const runnerArgs = Array.isArray(runner.args) ? runner.args.filter((arg): arg is string => typeof arg === "string") : undefined;
|
|
438
429
|
target.runner = { type: "external-cli", command: runner.command.trim(), ...(runnerArgs?.length ? { args: runnerArgs } : {}), ...(runner.promptDelivery ? { promptDelivery: "stdin" } : {}) };
|
|
439
|
-
} else
|
|
430
|
+
} else if (runner.type === "external-job" && typeof runner.provider === "string" && runner.provider.trim() === runner.provider && runner.provider
|
|
431
|
+
&& (runner.options === undefined || (runner.options && typeof runner.options === "object" && !Array.isArray(runner.options) && isJsonSerializable(runner.options)))
|
|
432
|
+
&& Object.keys(runner).every((key) => ["type", "provider", "options"].includes(key))) {
|
|
433
|
+
target.runner = { type: "external-job", provider: runner.provider, ...(runner.options ? { options: runner.options as Record<string, unknown> } : {}) };
|
|
434
|
+
} else return "config.runner must be { type: 'pi' }, { type: 'external-cli', command: string, args?: string[], promptDelivery?: 'stdin' }, or { type: 'external-job', provider: string, options?: object }.";
|
|
440
435
|
} else return "config.runner must be an object, false, or empty string when provided.";
|
|
441
436
|
}
|
|
442
437
|
if (hasKey(cfg, "model")) {
|
|
@@ -566,6 +561,10 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
|
|
|
566
561
|
else if (typeof cfg.output === "string") target.output = cfg.output;
|
|
567
562
|
else return "config.output must be a string or false when provided.";
|
|
568
563
|
}
|
|
564
|
+
if (hasKey(cfg, "outputMode")) {
|
|
565
|
+
if (cfg.outputMode === "inline" || cfg.outputMode === "file-only") target.outputMode = cfg.outputMode;
|
|
566
|
+
else return "config.outputMode must be 'inline' or 'file-only' when provided.";
|
|
567
|
+
}
|
|
569
568
|
if (hasKey(cfg, "reads")) {
|
|
570
569
|
if (cfg.reads === false || cfg.reads === "") delete target.defaultReads;
|
|
571
570
|
else if (typeof cfg.reads === "string") {
|
|
@@ -596,7 +595,7 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
|
|
|
596
595
|
target.toolBudget = cfg.toolBudget as ToolBudgetConfig;
|
|
597
596
|
}
|
|
598
597
|
}
|
|
599
|
-
if (target.runner?.type === "external-cli") {
|
|
598
|
+
if (target.runner?.type === "external-cli" || target.runner?.type === "external-job") {
|
|
600
599
|
const unsupported = [
|
|
601
600
|
target.tools?.length || target.mcpDirectTools?.length ? "tools" : undefined,
|
|
602
601
|
target.model ? "model" : undefined,
|
|
@@ -609,55 +608,40 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
|
|
|
609
608
|
target.completionGuard !== undefined ? "completionGuard" : undefined,
|
|
610
609
|
target.toolBudget ? "toolBudget" : undefined,
|
|
611
610
|
].filter((field): field is string => Boolean(field));
|
|
612
|
-
if (unsupported.length > 0) return `config.runner type '
|
|
611
|
+
if (unsupported.length > 0) return `config.runner type '${target.runner.type}' does not support Pi-only fields: ${unsupported.join(", ")}.`;
|
|
613
612
|
}
|
|
614
613
|
return undefined;
|
|
615
614
|
}
|
|
616
615
|
|
|
617
616
|
function resolveTarget<T extends { name: string; source: AgentSource; filePath: string }>(
|
|
618
|
-
kind: "agent" | "chain",
|
|
619
617
|
name: string,
|
|
620
618
|
matches: T[],
|
|
621
619
|
cwd: string,
|
|
622
620
|
scopeHint?: string,
|
|
623
621
|
): T | AgentToolResult<Details> {
|
|
624
|
-
const distinctNames = [...new Set(matches.map((
|
|
625
|
-
if (distinctNames.length > 1) {
|
|
626
|
-
|
|
627
|
-
}
|
|
628
|
-
const mutable = matches.filter((m): m is T & { source: ManagementScope } => isMutableSource(m.source));
|
|
622
|
+
const distinctNames = [...new Set(matches.map((match) => match.name))];
|
|
623
|
+
if (distinctNames.length > 1) return result(`Ambiguous agent alias or name '${name}': ${distinctNames.sort((a, b) => a.localeCompare(b)).join(", ")}`, true);
|
|
624
|
+
const mutable = matches.filter((match): match is T & { source: ManagementScope } => isMutableSource(match.source));
|
|
629
625
|
if (mutable.length === 0) {
|
|
630
|
-
if (matches.length > 0) {
|
|
631
|
-
|
|
632
|
-
}
|
|
633
|
-
const available = availableNames(cwd, kind);
|
|
634
|
-
return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' not found. Available: ${available.join(", ") || "none"}.`, true);
|
|
626
|
+
if (matches.length > 0) return result(`Agent '${name}' is read-only and cannot be modified. Create a same-named agent in user or project scope to override it.`, true);
|
|
627
|
+
return result(`Agent '${name}' not found. Available: ${availableAgentNames(cwd).join(", ") || "none"}.`, true);
|
|
635
628
|
}
|
|
636
629
|
if (mutable.length === 1) return mutable[0]!;
|
|
637
630
|
const scope = asDisambiguationScope(scopeHint);
|
|
638
631
|
if (!scope) {
|
|
639
|
-
const paths = mutable.map((
|
|
640
|
-
return result(
|
|
632
|
+
const paths = mutable.map((match) => `${match.source}: ${match.filePath}`).join("\n");
|
|
633
|
+
return result(`Agent '${name}' exists in both scopes. Specify agentScope: 'user' or 'project'.\n${paths}`, true);
|
|
641
634
|
}
|
|
642
|
-
const scoped = mutable.filter((
|
|
643
|
-
if (scoped.length === 0) return result(
|
|
644
|
-
if (scoped.length > 1) return result(`Multiple
|
|
635
|
+
const scoped = mutable.filter((match) => match.source === scope);
|
|
636
|
+
if (scoped.length === 0) return result(`Agent '${name}' not found in scope '${scope}'.`, true);
|
|
637
|
+
if (scoped.length > 1) return result(`Multiple agents named '${name}' found in scope '${scope}': ${scoped.map((match) => match.filePath).join(", ")}`, true);
|
|
645
638
|
return scoped[0]!;
|
|
646
639
|
}
|
|
647
640
|
|
|
648
|
-
function renamePath(
|
|
649
|
-
kind: "agent" | "chain",
|
|
650
|
-
currentPath: string,
|
|
651
|
-
newName: string,
|
|
652
|
-
scope: ManagementScope,
|
|
653
|
-
cwd: string,
|
|
654
|
-
): { filePath?: string; error?: string } {
|
|
641
|
+
function renamePath(currentPath: string, newName: string, scope: ManagementScope, cwd: string): { filePath?: string; error?: string } {
|
|
655
642
|
if (nameExistsInScope(cwd, scope, newName, currentPath)) return { error: `Name '${newName}' already exists in ${scope} scope.` };
|
|
656
|
-
const
|
|
657
|
-
|
|
658
|
-
if (fs.existsSync(filePath) && filePath !== currentPath) {
|
|
659
|
-
return { error: `File already exists at ${filePath} but is not a valid ${kind} definition. Remove or rename it first.` };
|
|
660
|
-
}
|
|
643
|
+
const filePath = path.join(path.dirname(currentPath), `${newName}.md`);
|
|
644
|
+
if (fs.existsSync(filePath) && filePath !== currentPath) return { error: `File already exists at ${filePath} but is not a valid agent definition. Remove or rename it first.` };
|
|
661
645
|
fs.renameSync(currentPath, filePath);
|
|
662
646
|
return { filePath };
|
|
663
647
|
}
|
|
@@ -690,6 +674,7 @@ function formatAgentDetail(agent: AgentConfig): string {
|
|
|
690
674
|
if (agent.subagentOnlyExtensions !== undefined) lines.push(`Subagent-only extensions: ${agent.subagentOnlyExtensions.length ? agent.subagentOnlyExtensions.join(", ") : "(none)"}`);
|
|
691
675
|
if (agent.thinking) lines.push(`Thinking: ${agent.thinking}`);
|
|
692
676
|
if (agent.output) lines.push(`Output: ${agent.output}`);
|
|
677
|
+
if (agent.outputMode) lines.push(`Output mode: ${agent.outputMode}`);
|
|
693
678
|
if (agent.defaultReads?.length) lines.push(`Reads: ${agent.defaultReads.join(", ")}`);
|
|
694
679
|
if (agent.defaultProgress) lines.push("Progress: true");
|
|
695
680
|
if (agent.maxSubagentDepth !== undefined) lines.push(`Max subagent depth: ${agent.maxSubagentDepth}`);
|
|
@@ -700,71 +685,28 @@ function formatAgentDetail(agent: AgentConfig): string {
|
|
|
700
685
|
return lines.join("\n");
|
|
701
686
|
}
|
|
702
687
|
|
|
703
|
-
function formatChainStepDetail(step: ChainStepConfig, index: number): string[] {
|
|
704
|
-
const lines: string[] = [];
|
|
705
|
-
if (step.expand || step.collect) {
|
|
706
|
-
const parallel = step.parallel && !Array.isArray(step.parallel) && typeof step.parallel === "object" ? step.parallel as { agent?: unknown; task?: unknown; label?: unknown; outputSchema?: unknown } : undefined;
|
|
707
|
-
const expand = step.expand && typeof step.expand === "object" ? step.expand as { from?: { output?: unknown; path?: unknown }; item?: unknown; key?: unknown; maxItems?: unknown; onEmpty?: unknown } : undefined;
|
|
708
|
-
const collect = step.collect && typeof step.collect === "object" ? step.collect as { as?: unknown; outputSchema?: unknown } : undefined;
|
|
709
|
-
lines.push(`${index + 1}. Dynamic fanout${typeof collect?.as === "string" ? ` -> ${collect.as}` : ""}`);
|
|
710
|
-
if (expand?.from) lines.push(` Expand: ${String(expand.from.output ?? "?")}${String(expand.from.path ?? "")}`);
|
|
711
|
-
if (typeof expand?.item === "string") lines.push(` Item variable: ${expand.item}`);
|
|
712
|
-
if (typeof expand?.key === "string") lines.push(` Key: ${expand.key}`);
|
|
713
|
-
if (typeof expand?.maxItems === "number") lines.push(` Max items: ${expand.maxItems}`);
|
|
714
|
-
if (typeof expand?.onEmpty === "string") lines.push(` On empty: ${expand.onEmpty}`);
|
|
715
|
-
if (parallel?.agent) lines.push(` Agent: ${String(parallel.agent)}`);
|
|
716
|
-
if (typeof parallel?.label === "string") lines.push(` Label: ${parallel.label}`);
|
|
717
|
-
if (typeof parallel?.task === "string" && parallel.task.trim()) lines.push(` Task: ${parallel.task}`);
|
|
718
|
-
if (parallel?.outputSchema) lines.push(" Structured output: true");
|
|
719
|
-
if (parallel && "toolBudget" in parallel) lines.push(` Tool budget: ${JSON.stringify((parallel as { toolBudget?: unknown }).toolBudget)}`);
|
|
720
|
-
if (collect?.outputSchema) lines.push(" Collect schema: true");
|
|
721
|
-
if (step.concurrency !== undefined) lines.push(` Concurrency: ${step.concurrency}`);
|
|
722
|
-
if (step.failFast !== undefined) lines.push(` Fail fast: ${step.failFast ? "true" : "false"}`);
|
|
723
|
-
return lines;
|
|
724
|
-
}
|
|
725
|
-
lines.push(`${index + 1}. ${step.agent}`);
|
|
726
|
-
if (step.task?.trim()) lines.push(` Task: ${step.task}`);
|
|
727
|
-
if (step.output === false) lines.push(" Output: false");
|
|
728
|
-
else if (step.output) lines.push(` Output: ${step.output}`);
|
|
729
|
-
if (step.outputMode) lines.push(` Output mode: ${step.outputMode}`);
|
|
730
|
-
if (step.toolBudget) lines.push(` Tool budget: ${JSON.stringify(step.toolBudget)}`);
|
|
731
|
-
if (step.reads === false) lines.push(" Reads: false");
|
|
732
|
-
else if (Array.isArray(step.reads) && step.reads.length > 0) lines.push(` Reads: ${step.reads.join(", ")}`);
|
|
733
|
-
if (step.model) lines.push(` Model: ${step.model}`);
|
|
734
|
-
if (step.skills === false) lines.push(" Skills: false");
|
|
735
|
-
else if (Array.isArray(step.skills) && step.skills.length > 0) lines.push(` Skills: ${step.skills.join(", ")}`);
|
|
736
|
-
if (step.progress !== undefined) lines.push(` Progress: ${step.progress ? "true" : "false"}`);
|
|
737
|
-
return lines;
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
function formatChainDetail(chain: ChainConfig): string {
|
|
741
|
-
const lines: string[] = [`Chain: ${chain.name} (${chain.source})`, `Path: ${chain.filePath}`, `Description: ${chain.description}`];
|
|
742
|
-
if (chain.packageName) {
|
|
743
|
-
lines.push(`Local name: ${frontmatterNameForConfig(chain)}`);
|
|
744
|
-
lines.push(`Package: ${chain.packageName}`);
|
|
745
|
-
}
|
|
746
|
-
lines.push("", "Steps:");
|
|
747
|
-
for (let i = 0; i < chain.steps.length; i++) {
|
|
748
|
-
lines.push(...formatChainStepDetail(chain.steps[i]!, i));
|
|
749
|
-
}
|
|
750
|
-
return lines.join("\n");
|
|
751
|
-
}
|
|
752
|
-
|
|
753
688
|
export function handleList(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
754
689
|
const scope = normalizeListScope(params.agentScope) ?? "both";
|
|
755
690
|
const d = discoverAgentsAll(ctx.cwd);
|
|
756
|
-
|
|
691
|
+
let scopedAgents = mergeAgentsForScope(scope, d.user, d.project, d.builtin, d.package);
|
|
692
|
+
if (ctx.runtimeAgentOwner && listRuntimeAgentConfigs(ctx.runtimeAgentOwner).length > 0) {
|
|
693
|
+
const configuredAgents: AgentConfig[] = [
|
|
694
|
+
...d.builtin,
|
|
695
|
+
...d.package,
|
|
696
|
+
...d.user,
|
|
697
|
+
...d.project,
|
|
698
|
+
];
|
|
699
|
+
scopedAgents = mergeRuntimeAgents(ctx.runtimeAgentOwner, { agents: scopedAgents }, configuredAgents).agents;
|
|
700
|
+
}
|
|
701
|
+
scopedAgents = scopedAgents
|
|
757
702
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
758
703
|
const capabilityCeiling = resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
|
|
759
704
|
const visibleAgents = scopedAgents.filter((a) => !a.disabled);
|
|
760
705
|
const agents = visibleAgents.filter((a) => isAgentAllowedByCapabilityCeiling(a.name, capabilityCeiling));
|
|
761
706
|
const restrictedAgents = visibleAgents.filter((a) => !isAgentAllowedByCapabilityCeiling(a.name, capabilityCeiling));
|
|
762
707
|
const restrictedSources = capabilityCeilingAgentRestrictionSources(capabilityCeiling);
|
|
763
|
-
const chains = d.chains.filter((c) => scope === "both" || c.source === "package" || c.source === scope).sort((a, b) => a.name.localeCompare(b.name));
|
|
764
|
-
const diagnostics = d.chainDiagnostics.filter((entry) => scope === "both" || entry.source === scope);
|
|
765
708
|
const proactiveSuggestions = buildProactiveSkillSubagentRecommendationLines({
|
|
766
709
|
agents,
|
|
767
|
-
chains,
|
|
768
710
|
...(ctx.config?.proactiveSkillSubagents !== undefined ? { config: ctx.config.proactiveSkillSubagents } : {}),
|
|
769
711
|
discoverAvailableSkills: () => discoverAvailableSkills(ctx.cwd),
|
|
770
712
|
});
|
|
@@ -778,11 +720,12 @@ export function handleList(params: ManagementParams, ctx: ManagementContext): Ag
|
|
|
778
720
|
`Restricted agents (not executable in this session${restrictedSources?.length ? `; capability ceiling: ${restrictedSources.join(", ")}` : ""}):`,
|
|
779
721
|
...restrictedAgents.map((a) => `- ${a.name} (${a.source}${a.aliases?.length ? `, aliases: ${a.aliases.join(", ")}` : ""}): ${a.description}`),
|
|
780
722
|
] : []),
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
723
|
+
...(d.agentDiagnostics?.length ? [
|
|
724
|
+
"",
|
|
725
|
+
"Invalid agent definitions:",
|
|
726
|
+
...d.agentDiagnostics.map((diagnostic) => `- ${diagnostic.name ?? diagnostic.filePath} (${diagnostic.source}): ${diagnostic.error}`),
|
|
727
|
+
] : []),
|
|
784
728
|
...(proactiveSuggestions.length ? ["", ...proactiveSuggestions] : []),
|
|
785
|
-
...(diagnostics.length ? ["", "Chain diagnostics:", ...diagnostics.map((entry) => `- ${entry.filePath}: ${entry.error}`)] : []),
|
|
786
729
|
];
|
|
787
730
|
return result(lines.join("\n"));
|
|
788
731
|
}
|
|
@@ -869,40 +812,23 @@ function handleModels(params: ManagementParams, ctx: ManagementContext): AgentTo
|
|
|
869
812
|
}
|
|
870
813
|
|
|
871
814
|
function handleGet(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
872
|
-
if (!params.agent
|
|
815
|
+
if (!params.agent) return result("Specify 'agent' for get.", true);
|
|
873
816
|
const scope = normalizeListScope(params.agentScope);
|
|
874
817
|
if (!scope) return result("agentScope must be 'user', 'project', or 'both' for get.", true);
|
|
875
|
-
const
|
|
876
|
-
const
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
} else {
|
|
890
|
-
anyFound = true;
|
|
891
|
-
blocks.push(...matches.map(formatAgentDetail));
|
|
892
|
-
}
|
|
893
|
-
}
|
|
894
|
-
if (params.chainName) {
|
|
895
|
-
const matches = findChains(params.chainName, ctx.cwd, scope);
|
|
896
|
-
if (!matches.length) {
|
|
897
|
-
const msg = `Chain '${params.chainName}' not found. Available: ${availableNames(ctx.cwd, "chain").join(", ") || "none"}.`;
|
|
898
|
-
if (!hasBoth) return result(msg, true);
|
|
899
|
-
blocks.push(msg);
|
|
900
|
-
} else {
|
|
901
|
-
anyFound = true;
|
|
902
|
-
blocks.push(...matches.map(formatChainDetail));
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
return result(blocks.join("\n\n"), !anyFound);
|
|
818
|
+
const discovered = discoverAgentsAll(ctx.cwd);
|
|
819
|
+
const matches = findAgentsInDiscovery(params.agent, discovered, scope);
|
|
820
|
+
const diagnostics = diagnosticsForScope(discovered.agentDiagnostics, scope);
|
|
821
|
+
const rawName = params.agent.trim();
|
|
822
|
+
const normalizedName = sanitizeName(rawName);
|
|
823
|
+
const diagnostic = findBlockingAgentDiagnostic(rawName, matches, diagnostics)
|
|
824
|
+
?? (normalizedName !== rawName ? findBlockingAgentDiagnostic(normalizedName, matches, diagnostics) : undefined);
|
|
825
|
+
if (diagnostic) return result(`Agent '${params.agent}' has invalid configuration: ${diagnostic.error}`, true);
|
|
826
|
+
const distinctNames = [...new Set(matches.map((agent) => agent.name))];
|
|
827
|
+
if (distinctNames.length > 1) return result(`Ambiguous agent alias or name '${params.agent}': ${distinctNames.sort((a, b) => a.localeCompare(b)).join(", ")}`, true);
|
|
828
|
+
if (!matches.length) {
|
|
829
|
+
return result(`Agent '${params.agent}' not found. Available: ${availableAgentNamesFromDiscovery(discovered).join(", ") || "none"}.`, true);
|
|
830
|
+
}
|
|
831
|
+
return result(matches.map(formatAgentDetail).join("\n\n"));
|
|
906
832
|
}
|
|
907
833
|
|
|
908
834
|
export function handleCreate(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
@@ -920,36 +846,16 @@ export function handleCreate(params: ManagementParams, ctx: ManagementContext):
|
|
|
920
846
|
const scopeRaw = cfg.scope ?? "user";
|
|
921
847
|
if (scopeRaw !== "user" && scopeRaw !== "project") return result("config.scope must be 'user' or 'project'.", true);
|
|
922
848
|
const scope = scopeRaw as ManagementScope;
|
|
923
|
-
|
|
849
|
+
if (hasKey(cfg, "steps")) return result("Durable chain definitions were removed; use workflowScript or /prompt-workflow for repeatable workflows.", true);
|
|
924
850
|
const d = discoverAgentsAll(ctx.cwd);
|
|
925
851
|
const projectConfigDir = getProjectConfigDir(ctx.cwd);
|
|
926
|
-
const targetDir =
|
|
927
|
-
? scope === "user" ? d.userChainDir : d.projectChainDir ?? path.join(projectConfigDir, "chains")
|
|
928
|
-
: scope === "user" ? d.userDir : d.projectDir ?? path.join(projectConfigDir, "agents");
|
|
852
|
+
const targetDir = scope === "user" ? d.userDir : d.projectDir ?? path.join(projectConfigDir, "agents");
|
|
929
853
|
fs.mkdirSync(targetDir, { recursive: true });
|
|
930
854
|
if (nameExistsInScope(ctx.cwd, scope, runtimeName)) return result(`Name '${runtimeName}' already exists in ${scope} scope. Use update instead.`, true);
|
|
931
|
-
const targetPath = path.join(targetDir,
|
|
932
|
-
if (fs.existsSync(targetPath)) return result(`File already exists at ${targetPath} but is not a valid
|
|
855
|
+
const targetPath = path.join(targetDir, `${runtimeName}.md`);
|
|
856
|
+
if (fs.existsSync(targetPath)) return result(`File already exists at ${targetPath} but is not a valid agent definition. Remove or rename it first.`, true);
|
|
933
857
|
const warnings: string[] = [];
|
|
934
|
-
if (
|
|
935
|
-
if (isChain) {
|
|
936
|
-
const parsed = parseStepList(cfg.steps);
|
|
937
|
-
if (parsed.error) return result(parsed.error, true);
|
|
938
|
-
const chain: ChainConfig = {
|
|
939
|
-
name: runtimeName,
|
|
940
|
-
localName: name,
|
|
941
|
-
...(parsedPackage.packageName !== undefined ? { packageName: parsedPackage.packageName } : {}),
|
|
942
|
-
description: cfg.description.trim(),
|
|
943
|
-
source: scope,
|
|
944
|
-
filePath: targetPath,
|
|
945
|
-
steps: parsed.steps!,
|
|
946
|
-
};
|
|
947
|
-
fs.writeFileSync(targetPath, serializeChain(chain), "utf-8");
|
|
948
|
-
const missing = unknownChainAgents(ctx.cwd, chain.steps);
|
|
949
|
-
if (missing.length) warnings.push(`Warning: chain steps reference unknown agents: ${missing.join(", ")}.`);
|
|
950
|
-
warnings.push(...chainStepWarnings(ctx, chain.steps));
|
|
951
|
-
return result([`Created chain '${runtimeName}' at ${targetPath}.`, ...warnings].join("\n"));
|
|
952
|
-
}
|
|
858
|
+
if (d.builtin.some((a) => a.name === runtimeName)) warnings.push(`Note: this shadows the builtin agent '${runtimeName}'.`);
|
|
953
859
|
const agent: AgentConfig = {
|
|
954
860
|
name: runtimeName,
|
|
955
861
|
localName: name,
|
|
@@ -975,75 +881,25 @@ export function handleCreate(params: ManagementParams, ctx: ManagementContext):
|
|
|
975
881
|
}
|
|
976
882
|
|
|
977
883
|
export function handleUpdate(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
978
|
-
if (!params.agent
|
|
979
|
-
if (params.agent && params.chainName) return result("Specify either 'agent' or 'chainName', not both.", true);
|
|
884
|
+
if (!params.agent) return result("Specify 'agent' for update.", true);
|
|
980
885
|
const parsedConfig = configObject(params.config);
|
|
981
886
|
if (parsedConfig.error) return result(parsedConfig.error, true);
|
|
982
887
|
const cfg = parsedConfig.value;
|
|
983
888
|
if (!cfg) return result("config required for update.", true);
|
|
889
|
+
if (hasKey(cfg, "steps")) return result("Durable chain definitions were removed; use workflowScript or /prompt-workflow for repeatable workflows.", true);
|
|
984
890
|
const warnings: string[] = [];
|
|
985
|
-
if (params.agent) {
|
|
986
|
-
const scopeHint = asDisambiguationScope(params.agentScope);
|
|
987
|
-
const targetOrError = resolveTarget("agent", params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
|
|
988
|
-
if ("content" in targetOrError) return targetOrError;
|
|
989
|
-
const target = targetOrError;
|
|
990
|
-
if (target.source !== "user" && target.source !== "project") return result(`Cannot update ${target.source} agent '${target.name}'. Eject it to user or project scope first.`, true);
|
|
991
|
-
const updated = editableAgentConfig(target);
|
|
992
|
-
const oldName = target.name;
|
|
993
|
-
if (hasKey(cfg, "name") && (typeof cfg.name !== "string" || !cfg.name.trim())) return result("config.name must be a non-empty string when provided.", true);
|
|
994
|
-
if (hasKey(cfg, "description") && (typeof cfg.description !== "string" || !cfg.description.trim())) return result("config.description must be a non-empty string when provided.", true);
|
|
995
|
-
let newLocalName = target.localName ?? frontmatterNameForConfig(target);
|
|
996
|
-
if (hasKey(cfg, "name")) {
|
|
997
|
-
newLocalName = sanitizeName(cfg.name as string);
|
|
998
|
-
if (!newLocalName) return result("config.name is invalid after sanitization.", true);
|
|
999
|
-
}
|
|
1000
|
-
let newPackageName = target.packageName;
|
|
1001
|
-
if (hasKey(cfg, "package")) {
|
|
1002
|
-
const parsedPackage = parsePackageConfig(cfg.package);
|
|
1003
|
-
if (parsedPackage.error) return result(parsedPackage.error, true);
|
|
1004
|
-
newPackageName = parsedPackage.packageName;
|
|
1005
|
-
}
|
|
1006
|
-
const applyError = applyAgentConfig(updated, cfg);
|
|
1007
|
-
if (applyError) return result(applyError, true);
|
|
1008
|
-
const preserveFrontmatterFields = preservedAgentFrontmatterFields(target, cfg);
|
|
1009
|
-
updated.localName = newLocalName;
|
|
1010
|
-
if (newPackageName !== undefined) updated.packageName = newPackageName;
|
|
1011
|
-
else delete updated.packageName;
|
|
1012
|
-
updated.name = buildRuntimeName(newLocalName, newPackageName);
|
|
1013
|
-
if (hasKey(cfg, "description")) updated.description = (cfg.description as string).trim();
|
|
1014
|
-
if (hasKey(cfg, "model")) {
|
|
1015
|
-
const mw = modelWarning(ctx, updated.model);
|
|
1016
|
-
if (mw) warnings.push(mw);
|
|
1017
|
-
}
|
|
1018
|
-
if (hasKey(cfg, "fallbackModels")) {
|
|
1019
|
-
const fmw = fallbackModelsWarning(ctx, updated.fallbackModels);
|
|
1020
|
-
if (fmw) warnings.push(fmw);
|
|
1021
|
-
}
|
|
1022
|
-
if (hasKey(cfg, "skills") || hasKey(cfg, "skillPath")) {
|
|
1023
|
-
const sw = skillsWarning(ctx.cwd, updated);
|
|
1024
|
-
if (sw) warnings.push(sw);
|
|
1025
|
-
}
|
|
1026
|
-
if (updated.name !== oldName) {
|
|
1027
|
-
const renamed = renamePath("agent", target.filePath, updated.name, target.source, ctx.cwd);
|
|
1028
|
-
if (renamed.error) return result(renamed.error, true);
|
|
1029
|
-
updated.filePath = renamed.filePath!;
|
|
1030
|
-
}
|
|
1031
|
-
fs.writeFileSync(updated.filePath, serializeAgent(updated, { preserveFrontmatterFields }), "utf-8");
|
|
1032
|
-
if (updated.name !== oldName) {
|
|
1033
|
-
const refs = discoverAgentsAll(ctx.cwd).chains.filter((c) => c.steps.some((s) => s.agent === oldName)).map((c) => `${c.name} (${c.source})`);
|
|
1034
|
-
if (refs.length) warnings.push(`Warning: chains still reference '${oldName}': ${refs.join(", ")}.`);
|
|
1035
|
-
}
|
|
1036
|
-
const headline = updated.name === oldName
|
|
1037
|
-
? `Updated agent '${updated.name}' at ${updated.filePath}.`
|
|
1038
|
-
: `Updated agent '${oldName}' to '${updated.name}' at ${updated.filePath}.`;
|
|
1039
|
-
return result([headline, ...warnings].join("\n"));
|
|
1040
|
-
}
|
|
1041
891
|
const scopeHint = asDisambiguationScope(params.agentScope);
|
|
1042
|
-
const targetOrError = resolveTarget(
|
|
892
|
+
const targetOrError = resolveTarget(params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
|
|
1043
893
|
if ("content" in targetOrError) return targetOrError;
|
|
1044
894
|
const target = targetOrError;
|
|
1045
|
-
if (target.source !== "user" && target.source !== "project") return result(`Cannot update ${target.source}
|
|
1046
|
-
|
|
895
|
+
if (target.source !== "user" && target.source !== "project") return result(`Cannot update ${target.source} agent '${target.name}'. Eject it to user or project scope first.`, true);
|
|
896
|
+
let updated: AgentConfig;
|
|
897
|
+
try {
|
|
898
|
+
updated = editableAgentConfig(target);
|
|
899
|
+
} catch (error) {
|
|
900
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
901
|
+
return result(`Could not reread agent definition ${target.filePath} before updating '${target.name}': ${message}`, true);
|
|
902
|
+
}
|
|
1047
903
|
const oldName = target.name;
|
|
1048
904
|
if (hasKey(cfg, "name") && (typeof cfg.name !== "string" || !cfg.name.trim())) return result("config.name must be a non-empty string when provided.", true);
|
|
1049
905
|
if (hasKey(cfg, "description") && (typeof cfg.description !== "string" || !cfg.description.trim())) return result("config.description must be a non-empty string when provided.", true);
|
|
@@ -1058,92 +914,330 @@ export function handleUpdate(params: ManagementParams, ctx: ManagementContext):
|
|
|
1058
914
|
if (parsedPackage.error) return result(parsedPackage.error, true);
|
|
1059
915
|
newPackageName = parsedPackage.packageName;
|
|
1060
916
|
}
|
|
1061
|
-
|
|
1062
|
-
if (
|
|
1063
|
-
|
|
1064
|
-
if (parsed.error) return result(parsed.error, true);
|
|
1065
|
-
parsedSteps = parsed.steps!;
|
|
1066
|
-
}
|
|
917
|
+
const applyError = applyAgentConfig(updated, cfg);
|
|
918
|
+
if (applyError) return result(applyError, true);
|
|
919
|
+
const preserveFrontmatterFields = preservedAgentFrontmatterFields(target, cfg);
|
|
1067
920
|
updated.localName = newLocalName;
|
|
1068
921
|
if (newPackageName !== undefined) updated.packageName = newPackageName;
|
|
1069
922
|
else delete updated.packageName;
|
|
1070
923
|
updated.name = buildRuntimeName(newLocalName, newPackageName);
|
|
1071
924
|
if (hasKey(cfg, "description")) updated.description = (cfg.description as string).trim();
|
|
1072
|
-
if (
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
925
|
+
if (hasKey(cfg, "model")) {
|
|
926
|
+
const mw = modelWarning(ctx, updated.model);
|
|
927
|
+
if (mw) warnings.push(mw);
|
|
928
|
+
}
|
|
929
|
+
if (hasKey(cfg, "fallbackModels")) {
|
|
930
|
+
const fmw = fallbackModelsWarning(ctx, updated.fallbackModels);
|
|
931
|
+
if (fmw) warnings.push(fmw);
|
|
932
|
+
}
|
|
933
|
+
if (hasKey(cfg, "skills") || hasKey(cfg, "skillPath")) {
|
|
934
|
+
const sw = skillsWarning(ctx.cwd, updated);
|
|
935
|
+
if (sw) warnings.push(sw);
|
|
1077
936
|
}
|
|
1078
937
|
if (updated.name !== oldName) {
|
|
1079
|
-
const renamed = renamePath(
|
|
938
|
+
const renamed = renamePath(target.filePath, updated.name, target.source, ctx.cwd);
|
|
1080
939
|
if (renamed.error) return result(renamed.error, true);
|
|
1081
940
|
updated.filePath = renamed.filePath!;
|
|
1082
941
|
}
|
|
1083
|
-
fs.writeFileSync(updated.filePath, updated
|
|
942
|
+
fs.writeFileSync(updated.filePath, serializeAgent(updated, { preserveFrontmatterFields }), "utf-8");
|
|
1084
943
|
const headline = updated.name === oldName
|
|
1085
|
-
? `Updated
|
|
1086
|
-
: `Updated
|
|
944
|
+
? `Updated agent '${updated.name}' at ${updated.filePath}.`
|
|
945
|
+
: `Updated agent '${oldName}' to '${updated.name}' at ${updated.filePath}.`;
|
|
1087
946
|
return result([headline, ...warnings].join("\n"));
|
|
1088
947
|
}
|
|
1089
948
|
|
|
1090
949
|
function handleDelete(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
1091
|
-
if (!params.agent
|
|
1092
|
-
if (params.agent && params.chainName) return result("Specify either 'agent' or 'chainName', not both.", true);
|
|
950
|
+
if (!params.agent) return result("Specify 'agent' for delete.", true);
|
|
1093
951
|
const scopeHint = asDisambiguationScope(params.agentScope);
|
|
1094
|
-
|
|
1095
|
-
const targetOrError = resolveTarget("agent", params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
|
|
1096
|
-
if ("content" in targetOrError) return targetOrError;
|
|
1097
|
-
const target = targetOrError;
|
|
1098
|
-
fs.unlinkSync(target.filePath);
|
|
1099
|
-
const refs = discoverAgentsAll(ctx.cwd).chains.filter((c) => c.steps.some((s) => s.agent === target.name)).map((c) => `${c.name} (${c.source})`);
|
|
1100
|
-
const lines = [`Deleted agent '${target.name}' at ${target.filePath}.`];
|
|
1101
|
-
if (refs.length) lines.push(`Warning: chains reference deleted agent '${target.name}': ${refs.join(", ")}.`);
|
|
1102
|
-
return result(lines.join("\n"));
|
|
1103
|
-
}
|
|
1104
|
-
const targetOrError = resolveTarget("chain", params.chainName!, findChains(params.chainName!, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
|
|
952
|
+
const targetOrError = resolveTarget(params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
|
|
1105
953
|
if ("content" in targetOrError) return targetOrError;
|
|
1106
954
|
const target = targetOrError;
|
|
1107
955
|
fs.unlinkSync(target.filePath);
|
|
1108
|
-
return result(`Deleted
|
|
956
|
+
return result(`Deleted agent '${target.name}' at ${target.filePath}.`);
|
|
1109
957
|
}
|
|
1110
958
|
|
|
1111
|
-
function
|
|
1112
|
-
|
|
1113
|
-
|
|
959
|
+
function isRelativeAgentResourcePath(value: string): boolean {
|
|
960
|
+
return value === "." || value === ".." || value.startsWith("./") || value.startsWith("../");
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* Upstream v0.53.0 resolves agent-frontmatter extension paths to absolute
|
|
965
|
+
* paths at discovery time, so a portable resource is any entry that is a
|
|
966
|
+
* path (relative or absolute) rather than a bare tool name.
|
|
967
|
+
*/
|
|
968
|
+
function isAgentResourcePath(value: string): boolean {
|
|
969
|
+
return isRelativeAgentResourcePath(value) || path.isAbsolute(value);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
function resolvePortableAgentResources(
|
|
973
|
+
entries: string[] | undefined,
|
|
974
|
+
sourceFilePath: string,
|
|
975
|
+
): { entries: string[] | undefined; resourcePaths: string[] } {
|
|
976
|
+
const baseDir = path.dirname(sourceFilePath);
|
|
977
|
+
const resourcePaths = (entries ?? []).flatMap((entry) =>
|
|
978
|
+
isAgentResourcePath(entry) ? [path.resolve(baseDir, entry)] : [],
|
|
979
|
+
);
|
|
980
|
+
return {
|
|
981
|
+
entries: entries?.map((entry) => isAgentResourcePath(entry) ? path.resolve(baseDir, entry) : entry),
|
|
982
|
+
resourcePaths,
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function portableEjectedAgentContent(source: AgentConfig): {
|
|
987
|
+
content?: string;
|
|
988
|
+
resourcePaths?: string[];
|
|
989
|
+
error?: EjectAgentDefinitionResult;
|
|
990
|
+
} {
|
|
991
|
+
let sourceContent: string;
|
|
992
|
+
try {
|
|
993
|
+
sourceContent = fs.readFileSync(source.filePath, "utf-8");
|
|
994
|
+
} catch (error) {
|
|
995
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
996
|
+
return {
|
|
997
|
+
error: {
|
|
998
|
+
ok: false,
|
|
999
|
+
code: "source_read_failed",
|
|
1000
|
+
message: `Failed to read source agent at ${source.filePath}: ${message}`,
|
|
1001
|
+
},
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
const extensions = resolvePortableAgentResources(source.extensions, source.filePath);
|
|
1006
|
+
const subagentOnlyExtensions = resolvePortableAgentResources(source.subagentOnlyExtensions, source.filePath);
|
|
1007
|
+
const skillPath = resolvePortableAgentResources(source.skillPath, source.filePath);
|
|
1008
|
+
const tools = resolvePortableAgentResources(source.tools, source.filePath);
|
|
1009
|
+
const resourcePaths = [...new Set([
|
|
1010
|
+
...extensions.resourcePaths,
|
|
1011
|
+
...subagentOnlyExtensions.resourcePaths,
|
|
1012
|
+
...skillPath.resourcePaths,
|
|
1013
|
+
...tools.resourcePaths,
|
|
1014
|
+
])].sort((a, b) => a.localeCompare(b));
|
|
1015
|
+
const missingResources = resourcePaths.filter((resourcePath) => !fs.existsSync(resourcePath));
|
|
1016
|
+
if (missingResources.length > 0) {
|
|
1017
|
+
return {
|
|
1018
|
+
error: {
|
|
1019
|
+
ok: false,
|
|
1020
|
+
code: "resource_missing",
|
|
1021
|
+
message: `Agent '${source.name}' cannot be ejected because its relative resource path(s) do not exist: ${missingResources.join(", ")}.`,
|
|
1022
|
+
},
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
if (resourcePaths.length === 0) return { content: sourceContent, resourcePaths };
|
|
1026
|
+
|
|
1027
|
+
const { frontmatter } = parseFrontmatter(sourceContent);
|
|
1028
|
+
const portableAgent: AgentConfig = {
|
|
1029
|
+
...source,
|
|
1030
|
+
...(source.extensions !== undefined ? { extensions: extensions.entries! } : {}),
|
|
1031
|
+
...(source.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: subagentOnlyExtensions.entries! } : {}),
|
|
1032
|
+
...(source.skillPath !== undefined ? { skillPath: skillPath.entries! } : {}),
|
|
1033
|
+
...(source.tools !== undefined ? { tools: tools.entries! } : {}),
|
|
1034
|
+
};
|
|
1035
|
+
return {
|
|
1036
|
+
content: serializeAgent(portableAgent, { preserveFrontmatterFields: new Set(Object.keys(frontmatter)) }),
|
|
1037
|
+
resourcePaths,
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
function cleanupEjectedFile(targetPath: string, expectedContent: string): void {
|
|
1042
|
+
try {
|
|
1043
|
+
if (fs.readFileSync(targetPath, "utf-8") === expectedContent) fs.unlinkSync(targetPath);
|
|
1044
|
+
} catch {
|
|
1045
|
+
// The service only cleans the file it created during this call.
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
function validateEjectedAgentLaunchPreflight(agent: AgentConfig, cwd: string): string | undefined {
|
|
1050
|
+
const resolvedSkills = resolveSkillsWithFallback(
|
|
1051
|
+
agent.skills ?? [],
|
|
1052
|
+
cwd,
|
|
1053
|
+
undefined,
|
|
1054
|
+
agent.skillPath,
|
|
1055
|
+
agent.filePath ? path.dirname(agent.filePath) : cwd,
|
|
1056
|
+
);
|
|
1057
|
+
if (resolvedSkills.missing.length > 0) {
|
|
1058
|
+
return `Missing skills: ${resolvedSkills.missing.join(", ")}`;
|
|
1059
|
+
}
|
|
1060
|
+
try {
|
|
1061
|
+
resolvePiLaunchToolPlan({
|
|
1062
|
+
tools: agent.tools,
|
|
1063
|
+
extensions: agent.extensions,
|
|
1064
|
+
subagentOnlyExtensions: agent.subagentOnlyExtensions,
|
|
1065
|
+
mcpDirectTools: agent.mcpDirectTools,
|
|
1066
|
+
cwd,
|
|
1067
|
+
requireReadTool: resolvedSkills.resolved.length > 0,
|
|
1068
|
+
agentName: agent.name,
|
|
1069
|
+
});
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
return error instanceof Error ? error.message : String(error);
|
|
1072
|
+
}
|
|
1073
|
+
return undefined;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/**
|
|
1077
|
+
* Shared extraction of the existing eject handler. It deliberately owns only
|
|
1078
|
+
* agent-definition copying, no-overwrite checks, project-trust input, and
|
|
1079
|
+
* portable package-relative resource paths.
|
|
1080
|
+
*/
|
|
1081
|
+
export function ejectAgentDefinition(input: EjectAgentDefinitionInput): EjectAgentDefinitionResult {
|
|
1082
|
+
const raw = input.agent.trim();
|
|
1114
1083
|
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);
|
|
1084
|
+
if (!raw || !sanitized) {
|
|
1085
|
+
return { ok: false, code: "invalid_agent", message: "agent must be a non-empty valid agent name." };
|
|
1122
1086
|
}
|
|
1123
|
-
|
|
1124
|
-
|
|
1087
|
+
if (input.scope !== "user" && input.scope !== "project") {
|
|
1088
|
+
return { ok: false, code: "invalid_agent", message: "scope must be 'user' or 'project'." };
|
|
1089
|
+
}
|
|
1090
|
+
if (input.scope === "project" && input.projectTrusted !== true) {
|
|
1091
|
+
return {
|
|
1092
|
+
ok: false,
|
|
1093
|
+
code: "untrusted_project",
|
|
1094
|
+
scope: input.scope,
|
|
1095
|
+
message: "Project scope ejection requires a trusted project. Trust the project and retry.",
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
let discovered: ReturnType<typeof discoverAgentsAll>;
|
|
1100
|
+
try {
|
|
1101
|
+
discovered = discoverAgentsAll(input.cwd);
|
|
1102
|
+
} catch (error) {
|
|
1103
|
+
return {
|
|
1104
|
+
ok: false,
|
|
1105
|
+
code: "rediscovery_failed",
|
|
1106
|
+
scope: input.scope,
|
|
1107
|
+
message: `Unable to discover agents before ejecting: ${error instanceof Error ? error.message : String(error)}`,
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
if (input.scope === "project" && discovered.projectDir === null) {
|
|
1111
|
+
return {
|
|
1112
|
+
ok: false,
|
|
1113
|
+
code: "missing_project_root",
|
|
1114
|
+
scope: input.scope,
|
|
1115
|
+
message: "Project scope ejection is not available here: no project config root (.pi or .agents) was found above the cwd.",
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
const existingCustom = (input.scope === "user" ? discovered.user : discovered.project)
|
|
1120
|
+
.find((candidate) => candidate.name === raw || candidate.name === sanitized);
|
|
1125
1121
|
if (existingCustom) {
|
|
1126
|
-
return
|
|
1122
|
+
return {
|
|
1123
|
+
ok: false,
|
|
1124
|
+
code: "existing_custom",
|
|
1125
|
+
scope: input.scope,
|
|
1126
|
+
targetPath: existingCustom.filePath,
|
|
1127
|
+
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.`,
|
|
1128
|
+
};
|
|
1127
1129
|
}
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
+
const bundledCandidates = input.scope === "user"
|
|
1131
|
+
? discoverAgents(input.cwd, "user").agents.filter((candidate) => candidate.source === "builtin" || candidate.source === "package")
|
|
1132
|
+
: [...discovered.package, ...discovered.builtin];
|
|
1133
|
+
const source = bundledCandidates.find((candidate) => candidate.name === raw || candidate.name === sanitized);
|
|
1134
|
+
if (!source) {
|
|
1135
|
+
return {
|
|
1136
|
+
ok: false,
|
|
1137
|
+
code: "missing_source",
|
|
1138
|
+
scope: input.scope,
|
|
1139
|
+
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: ${availableAgentNames(input.cwd).join(", ") || "none"}.`,
|
|
1140
|
+
};
|
|
1130
1141
|
}
|
|
1131
|
-
const
|
|
1132
|
-
|
|
1133
|
-
|
|
1142
|
+
const runtimeName = source.name;
|
|
1143
|
+
if (nameExistsInScope(input.cwd, input.scope, runtimeName)) {
|
|
1144
|
+
return {
|
|
1145
|
+
ok: false,
|
|
1146
|
+
code: "name_conflict",
|
|
1147
|
+
scope: input.scope,
|
|
1148
|
+
message: `An agent or chain named '${runtimeName}' already exists in ${input.scope} scope. Remove or rename it first.`,
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
const targetDir = input.scope === "user" ? discovered.userDir : discovered.projectDir!;
|
|
1134
1153
|
const targetPath = path.join(targetDir, `${runtimeName}.md`);
|
|
1135
1154
|
if (fs.existsSync(targetPath)) {
|
|
1136
|
-
return
|
|
1155
|
+
return {
|
|
1156
|
+
ok: false,
|
|
1157
|
+
code: "existing_file",
|
|
1158
|
+
scope: input.scope,
|
|
1159
|
+
targetPath,
|
|
1160
|
+
message: `File already exists at ${targetPath} but is not a valid agent definition. Remove or rename it first.`,
|
|
1161
|
+
};
|
|
1137
1162
|
}
|
|
1138
|
-
|
|
1163
|
+
|
|
1164
|
+
const portable = portableEjectedAgentContent(source);
|
|
1165
|
+
if (portable.error) return { ...portable.error, scope: input.scope, targetPath };
|
|
1166
|
+
const content = portable.content!;
|
|
1139
1167
|
try {
|
|
1140
|
-
|
|
1168
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
1169
|
+
fs.writeFileSync(targetPath, content, { encoding: "utf-8", flag: "wx" });
|
|
1141
1170
|
} catch (error) {
|
|
1142
1171
|
const message = error instanceof Error ? error.message : String(error);
|
|
1143
|
-
return
|
|
1172
|
+
return {
|
|
1173
|
+
ok: false,
|
|
1174
|
+
code: "write_failed",
|
|
1175
|
+
scope: input.scope,
|
|
1176
|
+
targetPath,
|
|
1177
|
+
message: `Failed to write ejected agent '${runtimeName}' at ${targetPath}: ${message}`,
|
|
1178
|
+
};
|
|
1144
1179
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1180
|
+
|
|
1181
|
+
const rediscovered = discoverAgentsAll(input.cwd);
|
|
1182
|
+
const copied = (input.scope === "user" ? rediscovered.user : rediscovered.project)
|
|
1183
|
+
.find((candidate) => candidate.name === runtimeName && path.resolve(candidate.filePath) === path.resolve(targetPath));
|
|
1184
|
+
if (!copied) {
|
|
1185
|
+
cleanupEjectedFile(targetPath, content);
|
|
1186
|
+
return {
|
|
1187
|
+
ok: false,
|
|
1188
|
+
code: "rediscovery_failed",
|
|
1189
|
+
scope: input.scope,
|
|
1190
|
+
targetPath,
|
|
1191
|
+
message: `Ejected agent '${runtimeName}' could not be rediscovered at ${targetPath}; no file was kept.`,
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
const preflightError = validateEjectedAgentLaunchPreflight(copied, input.cwd);
|
|
1196
|
+
if (preflightError) {
|
|
1197
|
+
cleanupEjectedFile(targetPath, content);
|
|
1198
|
+
return {
|
|
1199
|
+
ok: false,
|
|
1200
|
+
code: "preflight_failed",
|
|
1201
|
+
scope: input.scope,
|
|
1202
|
+
targetPath,
|
|
1203
|
+
message: `Ejected agent '${runtimeName}' failed launch preflight at ${targetPath}: ${preflightError}. No file was kept.`,
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
const sourceKind = source.source as "builtin" | "package";
|
|
1208
|
+
return {
|
|
1209
|
+
ok: true,
|
|
1210
|
+
code: "ejected",
|
|
1211
|
+
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.`,
|
|
1212
|
+
agent: runtimeName,
|
|
1213
|
+
source: sourceKind,
|
|
1214
|
+
scope: input.scope,
|
|
1215
|
+
targetPath,
|
|
1216
|
+
verification: {
|
|
1217
|
+
agent: copied.name,
|
|
1218
|
+
scope: input.scope,
|
|
1219
|
+
targetPath,
|
|
1220
|
+
source: sourceKind,
|
|
1221
|
+
resourcePaths: portable.resourcePaths ?? [],
|
|
1222
|
+
launchPreflighted: true,
|
|
1223
|
+
},
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
function handleEject(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
1228
|
+
if (!params.agent) return result("Specify 'agent' for eject.", true);
|
|
1229
|
+
const parsedScope = actionScope(params.agentScope, "eject");
|
|
1230
|
+
if (parsedScope.error) return parsedScope.error;
|
|
1231
|
+
const scope = parsedScope.scope!;
|
|
1232
|
+
const ejected = ejectAgentDefinition({
|
|
1233
|
+
cwd: ctx.cwd,
|
|
1234
|
+
agent: params.agent,
|
|
1235
|
+
scope,
|
|
1236
|
+
// Preserve the existing management-action behavior. Direct public callers
|
|
1237
|
+
// must supply affirmative project trust themselves.
|
|
1238
|
+
...(scope === "project" ? { projectTrusted: true } : {}),
|
|
1239
|
+
});
|
|
1240
|
+
return result(ejected.message, !ejected.ok);
|
|
1147
1241
|
}
|
|
1148
1242
|
|
|
1149
1243
|
function handleDisable(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
|
|
@@ -1159,7 +1253,7 @@ function handleDisable(params: ManagementParams, ctx: ManagementContext): AgentT
|
|
|
1159
1253
|
const effective = resolveEffectiveAgent(d, raw);
|
|
1160
1254
|
if (effective.error) return result(effective.error, true);
|
|
1161
1255
|
if (!effective.agent) {
|
|
1162
|
-
return result(`Agent '${raw}' not found. Available: ${
|
|
1256
|
+
return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
|
|
1163
1257
|
}
|
|
1164
1258
|
const runtimeName = effective.agent.name;
|
|
1165
1259
|
const settingsPath = mergeBuiltinAgentOverride(ctx.cwd, runtimeName, scope, { disabled: true });
|
|
@@ -1183,7 +1277,7 @@ function handleEnable(params: ManagementParams, ctx: ManagementContext): AgentTo
|
|
|
1183
1277
|
const effective = resolveEffectiveAgent(d, raw);
|
|
1184
1278
|
if (effective.error) return result(effective.error, true);
|
|
1185
1279
|
if (!effective.agent) {
|
|
1186
|
-
return result(`Agent '${raw}' not found. Available: ${
|
|
1280
|
+
return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
|
|
1187
1281
|
}
|
|
1188
1282
|
const runtimeName = effective.agent.name;
|
|
1189
1283
|
const { path: settingsPath, removed } = removeBuiltinAgentOverrideFields(ctx.cwd, runtimeName, scope, ["disabled"]);
|
|
@@ -1215,7 +1309,7 @@ function handleReset(params: ManagementParams, ctx: ManagementContext): AgentToo
|
|
|
1215
1309
|
if (custom) {
|
|
1216
1310
|
return result(`Agent '${raw}' has no bundled default to reset to. Use { action: "delete", agent: "${custom.name}" } to remove the custom ${custom.source} agent.`, true);
|
|
1217
1311
|
}
|
|
1218
|
-
return result(`Agent '${raw}' not found. Available: ${
|
|
1312
|
+
return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
|
|
1219
1313
|
}
|
|
1220
1314
|
const runtimeName = bundled.name;
|
|
1221
1315
|
const custom = (scope === "user" ? d.user : d.project).find((a) => a.name === raw || a.name === sanitized);
|