mirror of
https://bitbucket.org/siakitem/my-pi.git
synced 2026-10-26 10:45:22 +00:00
feat(pi-subagents): 重新启用子 Agent 并使用独立的子 Agent 提示词
- 根包恢复 file:./pi-subagents 依赖与 extensions/subagents.ts 加载 (排在 permission-system 之后、Tool Search 之前),并刷新根锁文件; Agent / get_subagent_result / steer_subagent 权限设为 allow, 子 Agent 内的实际操作仍逐个经权限系统并转发主会话。 - 新增 config/prompt/subagent/:执行者角色 preamble 与组合包自带的 general-purpose / Explore / Plan 定义(替换上游内置,去掉 bash find 冲突规则与写死的 Haiku 模型)。 - pi-subagents 新增 basePrompt / bundledAgentsDir / excludedExtensionPaths 选项:子 Agent 不再嵌入父会话提示词,身份标记置于开头;子会话排除 pi-ask-user。未传选项时保持上游行为。 - system-prompt.ts:customPrompt 自带开场白时不再覆盖(修复子 Agent 角色 与 <active_agent> 身份被抹掉);仅凭 customPrompt 上的 <active_agent> 识别子会话,routing 规则支持 scope,sections 支持 subagentExclude (子会话去掉 memory_policy 与 chrome_profile_bridge)。 - pi-hermes-memory:子会话只读,记忆/skill 写入工具返回错误,后台整理、 纠错检测、会话 flush 与索引写入全部跳过。 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent
b817d66a11
commit
360d8cffc8
@@ -1763,6 +1763,148 @@ describe("mandatory extension policy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("excluded extension paths", () => {
|
||||
function excludedEntry(name = "pi-ask-user"): { dir: string; path: string } {
|
||||
const dir = mkdtempSync(join(tmpdir(), "subagents-excluded-runner-"));
|
||||
const extDir = join(dir, name);
|
||||
mkdirSync(extDir, { recursive: true });
|
||||
const path = join(extDir, "index.ts");
|
||||
writeFileSync(path, "export default () => {};\n");
|
||||
return { dir, path };
|
||||
}
|
||||
|
||||
function setup(extensions: true | string[] | false, excludeExtensions?: string[]) {
|
||||
vi.mocked(getConfig).mockReturnValueOnce(makeConfig({ extensions, excludeExtensions }));
|
||||
vi.mocked(getAgentConfig).mockReturnValueOnce(
|
||||
makeAgentConfig({ extensions, excludeExtensions }),
|
||||
);
|
||||
vi.mocked(getToolNamesForType).mockReturnValueOnce(BUILTINS_7);
|
||||
}
|
||||
|
||||
it("removes the extension under extensions:true, tools and all", async () => {
|
||||
const fixture = excludedEntry();
|
||||
try {
|
||||
setup(true);
|
||||
withExtensions({
|
||||
[fixture.path]: ["ask_user_question"],
|
||||
"/ext/other.ts": ["other_tool"],
|
||||
});
|
||||
const { session } = createSession("OK");
|
||||
createAgentSession.mockResolvedValue({ session });
|
||||
const onToolActivity = vi.fn();
|
||||
|
||||
await runAgent(ctx, "Explore", "go", {
|
||||
pi,
|
||||
excludedExtensionPaths: [fixture.path],
|
||||
onToolActivity,
|
||||
});
|
||||
|
||||
// Exclusion forces the override on even though extensions:true + no
|
||||
// frontmatter excludes would otherwise skip it.
|
||||
expect(lastLoaderOpts().extensionsOverride).toBeDefined();
|
||||
expect(loaderExtensionsRef.current.extensions.map((e) => e.path))
|
||||
.not.toContain(fixture.path);
|
||||
const tools = lastToolsPassed();
|
||||
expect(tools).not.toContain("ask_user_question");
|
||||
expect(tools).toContain("other_tool");
|
||||
expect(onToolActivity).toHaveBeenCalledWith(expect.objectContaining({
|
||||
toolName: expect.stringContaining("excluded from subagent sessions"),
|
||||
}));
|
||||
} finally {
|
||||
rmSync(fixture.dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("removes the extension even when an `extensions:` name entry selects it", async () => {
|
||||
const fixture = excludedEntry();
|
||||
try {
|
||||
setup(["pi-ask-user"]);
|
||||
withExtensions({ [fixture.path]: ["ask_user_question"] });
|
||||
const { session } = createSession("OK");
|
||||
createAgentSession.mockResolvedValue({ session });
|
||||
const onToolActivity = vi.fn();
|
||||
|
||||
await runAgent(ctx, "Explore", "go", {
|
||||
pi,
|
||||
excludedExtensionPaths: [fixture.path],
|
||||
onToolActivity,
|
||||
});
|
||||
|
||||
expect(loaderExtensionsRef.current.extensions.map((e) => e.path))
|
||||
.not.toContain(fixture.path);
|
||||
expect(lastToolsPassed()).not.toContain("ask_user_question");
|
||||
expect(onToolActivity).toHaveBeenCalledWith(expect.objectContaining({
|
||||
toolName: expect.stringContaining("excluded from subagent sessions"),
|
||||
}));
|
||||
} finally {
|
||||
rmSync(fixture.dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("removes the extension even when an `extensions:` path entry requests it", async () => {
|
||||
const fixture = excludedEntry();
|
||||
try {
|
||||
setup([fixture.path]);
|
||||
withExtensions({ [fixture.path]: ["ask_user_question"] });
|
||||
const { session } = createSession("OK");
|
||||
createAgentSession.mockResolvedValue({ session });
|
||||
|
||||
await runAgent(ctx, "Explore", "go", {
|
||||
pi,
|
||||
excludedExtensionPaths: [fixture.path],
|
||||
});
|
||||
|
||||
expect(lastLoaderOpts().additionalExtensionPaths).toBeUndefined();
|
||||
expect(loaderExtensionsRef.current.extensions.map((e) => e.path))
|
||||
.not.toContain(fixture.path);
|
||||
expect(lastToolsPassed()).not.toContain("ask_user_question");
|
||||
} finally {
|
||||
rmSync(fixture.dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("is a no-op when empty — no override installed for wildcard agents", async () => {
|
||||
setup(["*"]);
|
||||
withExtensions({ "/ext/a.ts": ["tool_a"] });
|
||||
const { session } = createSession("OK");
|
||||
createAgentSession.mockResolvedValue({ session });
|
||||
|
||||
await runAgent(ctx, "Explore", "go", { pi, excludedExtensionPaths: [] });
|
||||
|
||||
expect(lastLoaderOpts().extensionsOverride).toBeUndefined();
|
||||
expect(lastToolsPassed()).toContain("tool_a");
|
||||
});
|
||||
|
||||
it("keeps mandatory entries while removing excluded ones", async () => {
|
||||
const mandatoryDir = mkdtempSync(join(tmpdir(), "subagents-mandatory-runner-"));
|
||||
const mandatoryPath = join(mandatoryDir, "permission-system.ts");
|
||||
writeFileSync(mandatoryPath, "export default () => {};\n");
|
||||
const fixture = excludedEntry();
|
||||
try {
|
||||
setup(true);
|
||||
withExtensions({
|
||||
[mandatoryPath]: ["permission_admin"],
|
||||
[fixture.path]: ["ask_user_question"],
|
||||
});
|
||||
const { session } = createSession("OK");
|
||||
createAgentSession.mockResolvedValue({ session });
|
||||
|
||||
await runAgent(ctx, "Explore", "go", {
|
||||
pi,
|
||||
mandatoryExtensionPaths: [mandatoryPath],
|
||||
excludedExtensionPaths: [fixture.path],
|
||||
});
|
||||
|
||||
const loaded = loaderExtensionsRef.current.extensions.map((e) => e.path);
|
||||
expect(loaded).toContain(mandatoryPath);
|
||||
expect(loaded).not.toContain(fixture.path);
|
||||
} finally {
|
||||
rmSync(mandatoryDir, { recursive: true, force: true });
|
||||
rmSync(fixture.dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent-runner extension allowlist", () => {
|
||||
function setupArrayAgent(extensions: string[]) {
|
||||
vi.mocked(getConfig).mockReturnValueOnce(makeConfig({ extensions }));
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* bundled-agents.test.ts — `bundledAgentsDir` extension option: bundle-shipped
|
||||
* agent .md files register as embedded defaults (isDefault, no source/path),
|
||||
* sit between embedded defaults and user agents in precedence, and stay out of
|
||||
* the registry when the option is unset.
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { buildAgentRegistry, getAgentConfig, getDefaultAgentNames, registerAgents } from "../src/agent-types.js";
|
||||
import { loadBundledAgents } from "../src/custom-agents.js";
|
||||
import { createPiSubagentsExtension } from "../src/index.js";
|
||||
|
||||
let tmpDir: string;
|
||||
let bundledDir: string;
|
||||
let originalHome: string | undefined;
|
||||
let originalAgentDir: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = mkdtempSync(join(tmpdir(), "pi-bundled-agents-"));
|
||||
bundledDir = join(tmpDir, "bundled");
|
||||
mkdirSync(bundledDir, { recursive: true });
|
||||
originalHome = process.env.HOME;
|
||||
originalAgentDir = process.env.PI_CODING_AGENT_DIR;
|
||||
process.env.HOME = join(tmpDir, "home");
|
||||
delete process.env.PI_CODING_AGENT_DIR;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalHome == null) delete process.env.HOME;
|
||||
else process.env.HOME = originalHome;
|
||||
if (originalAgentDir == null) delete process.env.PI_CODING_AGENT_DIR;
|
||||
else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
|
||||
rmSync(tmpDir, { recursive: true, force: true });
|
||||
registerAgents(new Map());
|
||||
});
|
||||
|
||||
function writeBundled(name: string, content: string) {
|
||||
writeFileSync(join(bundledDir, `${name}.md`), content);
|
||||
}
|
||||
|
||||
describe("loadBundledAgents", () => {
|
||||
it("parses agent files with the custom-agent parser and stamps them as built-ins", () => {
|
||||
writeBundled("scout", `---
|
||||
name: scout
|
||||
description: Bundle scout
|
||||
prompt_mode: append
|
||||
tools: read, grep
|
||||
---
|
||||
|
||||
Bundle prompt body.`);
|
||||
|
||||
const agents = loadBundledAgents(bundledDir);
|
||||
const scout = agents.get("scout");
|
||||
expect(scout).toBeDefined();
|
||||
expect(scout?.description).toBe("Bundle scout");
|
||||
expect(scout?.systemPrompt).toBe("Bundle prompt body.");
|
||||
expect(scout?.promptMode).toBe("append");
|
||||
expect(scout?.builtinToolNames).toEqual(["read", "grep"]);
|
||||
expect(scout?.isDefault).toBe(true);
|
||||
expect(scout?.source).toBeUndefined();
|
||||
expect(scout?.sourcePath).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns an empty map for a missing or empty directory", () => {
|
||||
expect(loadBundledAgents(join(tmpDir, "missing")).size).toBe(0);
|
||||
expect(loadBundledAgents(bundledDir).size).toBe(0);
|
||||
});
|
||||
|
||||
it("skips non-.md files and reserved ':' names", () => {
|
||||
writeBundled("fine", "---\ndescription: ok\n---\nbody");
|
||||
writeFileSync(join(bundledDir, "notes.txt"), "not an agent");
|
||||
writeBundled("bad", "---\nname: 'plugin:scout'\ndescription: bad\n---\nbody");
|
||||
const agents = loadBundledAgents(bundledDir);
|
||||
expect([...agents.keys()]).toEqual(["fine"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bundled agent precedence", () => {
|
||||
it("replaces a same-name embedded default and reports as a default", () => {
|
||||
writeBundled("Explore", `---
|
||||
name: Explore
|
||||
description: Bundled Explore override
|
||||
prompt_mode: replace
|
||||
---
|
||||
|
||||
Bundled Explore body.`);
|
||||
|
||||
const bundled = loadBundledAgents(bundledDir);
|
||||
const registry = buildAgentRegistry(new Map(), bundled);
|
||||
expect(registry.get("Explore")?.systemPrompt).toBe("Bundled Explore body.");
|
||||
expect(registry.get("Explore")?.isDefault).toBe(true);
|
||||
// Unrelated embedded defaults are untouched.
|
||||
expect(registry.get("general-purpose")?.systemPrompt).not.toBe("Bundled Explore body.");
|
||||
});
|
||||
|
||||
it("new bundled names join the default set", () => {
|
||||
writeBundled("bundle-only", "---\ndescription: only in bundle\n---\nbody");
|
||||
const registry = buildAgentRegistry(new Map(), loadBundledAgents(bundledDir));
|
||||
expect(registry.get("bundle-only")?.isDefault).toBe(true);
|
||||
registerAgents(new Map(), loadBundledAgents(bundledDir));
|
||||
expect(getDefaultAgentNames()).toContain("bundle-only");
|
||||
expect(getAgentConfig("bundle-only")?.description).toBe("only in bundle");
|
||||
});
|
||||
|
||||
it("user agents still override bundled definitions", () => {
|
||||
writeBundled("scout", "---\ndescription: bundled\n---\nbundled body");
|
||||
const user = new Map([
|
||||
["scout", {
|
||||
name: "scout",
|
||||
description: "project override",
|
||||
systemPrompt: "project body",
|
||||
promptMode: "replace" as const,
|
||||
extensions: true as const,
|
||||
skills: true as const,
|
||||
source: "project" as const,
|
||||
sourcePath: "/proj/.pi/agents/scout.md",
|
||||
}],
|
||||
]);
|
||||
const registry = buildAgentRegistry(user, loadBundledAgents(bundledDir));
|
||||
expect(registry.get("scout")?.description).toBe("project override");
|
||||
expect(registry.get("scout")?.isDefault).not.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extension option validation", () => {
|
||||
it("rejects a path that is both mandatory and excluded", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "pi-subagents-overlap-"));
|
||||
const path = join(dir, "permission-system.ts");
|
||||
writeFileSync(path, "export default () => {};\n");
|
||||
expect(() =>
|
||||
createPiSubagentsExtension({
|
||||
mandatoryExtensionPaths: [path],
|
||||
excludedExtensionPaths: [path],
|
||||
}),
|
||||
).toThrow("both mandatory and excluded");
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("canonicalizes bundledAgentsDir and rejects missing directories", () => {
|
||||
expect(() =>
|
||||
createPiSubagentsExtension({ bundledAgentsDir: join(tmpDir, "missing") }),
|
||||
).toThrow("is unavailable");
|
||||
expect(() => createPiSubagentsExtension({ bundledAgentsDir: bundledDir })).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -433,4 +433,116 @@ describe("buildAgentPrompt", () => {
|
||||
expect(prompt.indexOf("<worktree_isolation>")).toBeGreaterThan(prompt.indexOf("<sub_agent_context>"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("host-owned base prompt", () => {
|
||||
const BASE = "You are a subagent operating inside pi. The human user does not see your messages.";
|
||||
|
||||
function baseConfig(promptMode: "append" | "replace", systemPrompt = "Custom instructions."): AgentConfig {
|
||||
return {
|
||||
name: "bundled-agent",
|
||||
description: "Bundled",
|
||||
builtinToolNames: [],
|
||||
extensions: true,
|
||||
skills: true,
|
||||
systemPrompt,
|
||||
promptMode,
|
||||
inheritContext: false,
|
||||
runInBackground: false,
|
||||
isolated: false,
|
||||
};
|
||||
}
|
||||
|
||||
it("append mode: replaces parent prompt and drops the bridge, keeps env/instructions/tag", () => {
|
||||
const prompt = buildAgentPrompt(
|
||||
baseConfig("append"),
|
||||
"/workspace",
|
||||
env,
|
||||
"SECRET parent prompt content",
|
||||
undefined,
|
||||
BASE,
|
||||
);
|
||||
// No inherited parent prefix to keep cacheable, so the tag leads the
|
||||
// prompt — same position as replace mode — and lets early session hooks
|
||||
// identify the child before before_agent_start.
|
||||
expect(prompt.startsWith('<active_agent name="bundled-agent"/>')).toBe(true);
|
||||
expect(prompt).not.toContain("SECRET parent prompt content");
|
||||
expect(prompt).not.toContain("<sub_agent_context>");
|
||||
expect(prompt).not.toContain("You are a pi coding agent sub-agent");
|
||||
expect(prompt).toContain("Working directory: /workspace");
|
||||
expect(prompt).toContain("<agent_instructions>");
|
||||
expect(prompt).toContain("Custom instructions.");
|
||||
expect(prompt.match(/<active_agent name="bundled-agent"\/>/g)).toHaveLength(1);
|
||||
const order = [
|
||||
'<active_agent name="bundled-agent"/>',
|
||||
BASE,
|
||||
"# Environment",
|
||||
"<agent_instructions>",
|
||||
].map((s) => prompt.indexOf(s));
|
||||
expect(order.every((i) => i >= 0)).toBe(true);
|
||||
expect(order).toEqual([...order].sort((a, b) => a - b));
|
||||
});
|
||||
|
||||
it("replace mode: drops the sub-agent header, keeps env + config prompt + tag", () => {
|
||||
const prompt = buildAgentPrompt(
|
||||
baseConfig("replace", "You are a read-only search agent."),
|
||||
"/workspace",
|
||||
env,
|
||||
"SECRET parent prompt content",
|
||||
undefined,
|
||||
BASE,
|
||||
);
|
||||
expect(prompt).not.toContain("You are a pi coding agent sub-agent");
|
||||
expect(prompt).not.toContain("SECRET parent prompt content");
|
||||
expect(prompt).not.toContain("<sub_agent_context>");
|
||||
expect(prompt).toContain("Working directory: /workspace");
|
||||
expect(prompt).toContain("You are a read-only search agent.");
|
||||
expect(prompt.match(/<active_agent name="bundled-agent"\/>/g)).toHaveLength(1);
|
||||
// The tag leads, then base, then env, then the config's system prompt.
|
||||
const order = [
|
||||
'<active_agent name="bundled-agent"/>',
|
||||
BASE,
|
||||
"# Environment",
|
||||
"You are a read-only search agent.",
|
||||
].map((s) => prompt.indexOf(s));
|
||||
expect(order.every((i) => i >= 0)).toBe(true);
|
||||
expect(order).toEqual([...order].sort((a, b) => a - b));
|
||||
});
|
||||
|
||||
it("keeps worktree and extras blocks", () => {
|
||||
const prompt = buildAgentPrompt(
|
||||
baseConfig("append"),
|
||||
"/wt/copy",
|
||||
env,
|
||||
undefined,
|
||||
{ worktreeBase: "/repo", memoryBlock: "# Agent Memory\nRemember this." },
|
||||
BASE,
|
||||
);
|
||||
expect(prompt).toContain("isolated git worktree copy of /repo");
|
||||
expect(prompt).toContain("# Agent Memory");
|
||||
expect(prompt).not.toContain("<sub_agent_context>");
|
||||
});
|
||||
|
||||
it("empty agent systemPrompt yields no agent_instructions in append mode", () => {
|
||||
const prompt = buildAgentPrompt(
|
||||
baseConfig("append", ""),
|
||||
"/workspace",
|
||||
env,
|
||||
"Parent.",
|
||||
undefined,
|
||||
BASE,
|
||||
);
|
||||
expect(prompt).not.toContain("<agent_instructions>");
|
||||
});
|
||||
|
||||
it("blank base keeps upstream composition byte-for-byte", () => {
|
||||
for (const promptMode of ["append", "replace"] as const) {
|
||||
const config = baseConfig(promptMode);
|
||||
for (const blank of [undefined, "", " \n "]) {
|
||||
expect(buildAgentPrompt(config, "/workspace", env, "Parent.", undefined, blank)).toBe(
|
||||
buildAgentPrompt(config, "/workspace", env, "Parent."),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user