Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/pi-interactive-subagents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ https://github.com/user-attachments/assets/30adb156-cfb4-4c47-84ca-dd4aa80cba9f

Call `subagent()` and it **returns immediately**. The sub-agent runs in its own terminal pane. A live widget above the input shows all running agents with their current state — `starting`, `active`, `waiting`, `stalled`, or `running`. When a sub-agent finishes, its result is **steered back** into the main session as an async notification — triggering a new turn so the agent can process it. Completion reminders are injected only after the model stops normally; user aborts and provider errors stay quiet.

Spawn and resume pass the resolved mode as `PI_SUBAGENT_INTERACTIVE=1|0`; child extensions must use this explicit value rather than infer it from `PI_SUBAGENT_AUTO_EXIT`. When `pi-session-tools:squash-completed` reports a successful `next-user` squash, only autonomous (`0`) children may receive one delayed completion reminder. Disabled reminders, manual takeover, interruption, new activity, stale session/leaf events, and already-reported completion suppress it; `auto` squashes and interactive children never receive this compensation.

```
╭─ Subagents ──────────────────────────── 2 running ─╮
│ 00:23 Scout: Auth (scout) active · bash 7m │
Expand Down
2 changes: 2 additions & 0 deletions packages/pi-interactive-subagents/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

调用 `subagent()` 后**立即返回**,子 agent 在自己的终端分屏中运行。输入框上方的实时 widget 展示所有运行中的 agent 及其状态(`starting`、`active`、`waiting`、`stalled`、`running`)。子 agent 完成后,结果以异步通知形式**回流**到主会话,触发新一轮处理。完成提醒仅在模型正常停止后注入;用户手动终止或提供方异常不会触发。

spawn 与 resume 会传入已解析的实际模式 `PI_SUBAGENT_INTERACTIVE=1|0`;子扩展必须使用该显式值,不能从 `PI_SUBAGENT_AUTO_EXIT` 猜测。收到 `pi-session-tools:squash-completed` 的成功 `next-user` 压缩事件时,只有自主子 agent(`0`)最多补偿一次延迟完成提醒。禁用提醒、人工接管、中断、新活动、过期 session/leaf 事件和已上报完成都会抑制提醒;`auto` 压缩和交互子 agent 不会收到此补偿。

由编排器启动的 agent 不出现在这个 widget 里:通过 `__pi_subagents` 桥并带上 `hiddenFromWidget: true` 启动的子 agent(目前是 `pi-dynamic-workflows` 的每个 `agent()`)会被排除,因为这些 agent 已由 Workflow 面板展示。隐藏只影响展示,子 agent 仍在运行集合中,监听、状态判定、中断和结果回流都照常工作。如果本次运行只有 workflow 子 agent,就完全不显示 Subagents widget。

```typescript
Expand Down
4 changes: 4 additions & 0 deletions packages/pi-interactive-subagents/locales/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
"zh-CN": "【自动提醒】\n• 已完成 → 调用 subagent_done 结束。\n• 结束前自检:是否在原地打转?若是,立刻收敛结果,用 caller_ping 抛回主 agent,不要过度思考。\n• 还在处理 → 忽略。",
"en-US": "[Auto reminder]\n• Done → call subagent_done to finish.\n• Before finishing, self-check: are you spinning in place? If so, converge your result immediately and hand it back to the main agent with caller_ping — don't overthink.\n• Still working → ignore."
},
"squashCompletionNudge": {
"zh-CN": "【压缩完成提醒】\n• 任务状态已保存,且当前正在等待上级输入。\n• 若已完成 → 调用 subagent_done 上报结果。\n• 需要主 agent 协助 → 调用 caller_ping;仍在处理 → 忽略。",
"en-US": "[Compaction completion reminder]\n• Your task state has been saved and the session is waiting for the parent.\n• If done → call subagent_done to report your result.\n• Need help from the main agent → call caller_ping; still working → ignore."
},
"muxCommandDescription": {
"zh-CN": "配置 subagent 使用的终端复用器及 Herdr 布局模式",
"en-US": "Configure the subagent multiplexer and Herdr layout mode"
Expand Down
2 changes: 1 addition & 1 deletion packages/pi-interactive-subagents/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"SKILL.md"
],
"scripts": {
"test": "tsx --test test/subagent-done-nudge.test.ts test/test.ts",
"test": "tsx --test test/subagent-done-nudge.test.ts test/squash-done-integration.test.ts test/test.ts",
"test:integration": "tsx --test --test-concurrency=1 test/integration/*.test.ts",
"typecheck": "tsc --noEmit --pretty false",
"build": "npm run typecheck",
Expand Down
10 changes: 10 additions & 0 deletions packages/pi-interactive-subagents/pi-extension/subagents/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,11 @@ const NO_EXTENSIONS_FLAG = "--no-extensions";
const EXTENSION_FLAG = "--extension";
const SUBAGENT_DONE_EXTENSION_FILE = "subagent-done.ts";

/** 将父端解析后的实际交互模式编码为子进程环境变量。 */
function buildSubagentInteractiveEnvironment(isInteractive: boolean): string {
return `PI_SUBAGENT_INTERACTIVE=${isInteractive ? "1" : "0"}`;
}

/**
* Build the child --tools allowlist.
*
Expand Down Expand Up @@ -1596,6 +1601,7 @@ export const __test__ = {
resolveEffectiveSessionMode,
resolveLaunchBehavior,
resolveEffectiveInteractive,
buildSubagentInteractiveEnvironment,
buildSubagentToolAllowlist,
buildChildExtensionArgs,
buildPiPromptArgs,
Expand Down Expand Up @@ -1838,6 +1844,8 @@ async function launchSubagent(
if (agentDefs?.autoExit) {
envParts.push(`PI_SUBAGENT_AUTO_EXIT=1`);
}
// 传递已解析的实际模式;子进程不得从 autoExit 推断是否为交互会话。
envParts.push(buildSubagentInteractiveEnvironment(effectiveInteractive));
envParts.push(`PI_SUBAGENT_SESSION=${shellEscape(subagentSessionFile)}`);
envParts.push(`PI_SUBAGENT_ID=${shellEscape(id)}`);
envParts.push(`PI_SUBAGENT_ACTIVITY_FILE=${shellEscape(activityFile)}`);
Expand Down Expand Up @@ -2564,6 +2572,8 @@ export default function subagentsExtension(pi: ExtensionAPI) {
if (autoExit) {
resumeEnvParts.push(`PI_SUBAGENT_AUTO_EXIT=1`);
}
// resume 的模式由显式 autoExit 参数解析后传递,避免子进程自行猜测。
resumeEnvParts.push(buildSubagentInteractiveEnvironment(interactive));
const resumeEnvPrefix = resumeEnvParts.join(" ") + " ";

const command = `${resumeEnvPrefix}${parts.join(" ")}; echo '__SUBAGENT_DONE_'$?'__'`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,22 @@ const i18n = createTranslator(loadCatalog(new URL("../../locales/index.json", im
const ASSISTANT_ROLE = "assistant";
const NORMAL_STOP_REASON = "stop";
const ABORTED_STOP_REASON = "aborted";
const SQUASH_COMPLETED_EVENT = "pi-session-tools:squash-completed";

type SquashCompletedEvent = {
sessionId: string;
leafId: string;
continuation: "auto" | "next-user";
};

/** 只接受 session-tools 公共事件的完整、可验证载荷。 */
function isSquashCompletedEvent(value: unknown): value is SquashCompletedEvent {
if (!value || typeof value !== "object") return false;
const event = value as Partial<SquashCompletedEvent>;
return typeof event.sessionId === "string"
&& typeof event.leafId === "string"
&& (event.continuation === "auto" || event.continuation === "next-user");
}

/** Treat input as manual takeover only after the first agent run has started. */
export function shouldMarkUserTookOver(agentStarted: boolean): boolean {
Expand Down Expand Up @@ -87,6 +103,8 @@ export default function (pi: ExtensionAPI) {
const deniedTools = new Set(parseDeniedTools(process.env.PI_DENY_TOOLS));
const denied = [...deniedTools];
const autoExit = process.env.PI_SUBAGENT_AUTO_EXIT === "1";
// 仅信任父端显式传入的实际模式;兼容旧父端时保守视为交互会话,不补偿提醒。
const isAutonomous = process.env.PI_SUBAGENT_INTERACTIVE === "0";
const recorder = createSubagentActivityRecorder({
runningChildId: process.env.PI_SUBAGENT_ID,
activityFile: process.env.PI_SUBAGENT_ACTIVITY_FILE,
Expand All @@ -103,7 +121,12 @@ export default function (pi: ExtensionAPI) {

let doneCalled = false;
let userInputAfterAgentEnd = false;
let isAgentAborted = false;
let isAgentActive = false;
let activityGeneration = 0;
let activeSessionContext: ExtensionContext | null = null;
let nudgeTimer: ReturnType<typeof setTimeout> | null = null;
const handledSquashEvents = new Set<string>();

/** Cancel and forget the pending completion reminder, if any. */
function clearNudgeTimer(): void {
Expand All @@ -113,31 +136,68 @@ export default function (pi: ExtensionAPI) {
}
}

/** 新输入、运行或结束会使已排队的提醒候选失效。 */
function invalidateNudge(): void {
activityGeneration += 1;
clearNudgeTimer();
}

/** 压缩事件到达时重新确认仍是同一空闲 session 和 leaf。 */
function isCurrentSquashEvent(event: SquashCompletedEvent, generation: number): boolean {
const sessionManager = activeSessionContext?.sessionManager;
return generation === activityGeneration
&& !doneCalled
&& !userInputAfterAgentEnd
&& !userTookOver
&& !isAgentAborted
&& !isAgentActive
&& activeSessionContext?.isIdle() === true
&& activeSessionContext.hasPendingMessages() === false
&& sessionManager?.getSessionId() === event.sessionId
&& sessionManager.getLeafId() === event.leafId;
}

/**
* After a subagent stops normally, schedule a nudge reminding it to call
* subagent_done if it hasn't already. Error and aborted runs are excluded.
*
* Each call replaces any pending nudge, so repeated agent_end events
* automatically reset the timer. The nudge only fires if no new agent
* activity or user input arrives within NUDGE_DELAY_MS.
* 在当前 idle 状态保持到延迟结束时才发送提醒,避免旧 session 的队列泄漏到新活动。
* 每次调用替换旧 timer,保留正常 stop 的既有单次提醒语义。
*/
function scheduleAgentEndNudge(): void {
function scheduleAgentEndNudge(
messageKey: "agentEndNudge" | "squashCompletionNudge" = "agentEndNudge",
stillEligible: () => boolean = () => !doneCalled && !userInputAfterAgentEnd,
): void {
clearNudgeTimer();
// 不论 autoExit 是否启用,都必须 nudge — autoExit 已被移除,
// agent 正常结束 turn 后只能靠主动调用 subagent_done 才能真正退出。
if (NUDGE_DISABLED || doneCalled) return;
if (NUDGE_DISABLED || doneCalled || !stillEligible()) return;

nudgeTimer = setTimeout(() => {
nudgeTimer = null;
if (doneCalled || userInputAfterAgentEnd) return;
if (!stillEligible()) return;

pi.sendUserMessage(
i18n.t("agentEndNudge"),
i18n.t(messageKey),
{ deliverAs: "followUp" },
);
}, NUDGE_DELAY_MS);
}

/** 仅自主子 Agent 的成功 next-user 压缩可补偿一次完成提醒。 */
function scheduleSquashCompletionNudge(event: SquashCompletedEvent): void {
if (event.continuation !== "next-user" || !isAutonomous || NUDGE_DISABLED) return;

const eventKey = `${event.sessionId}:${event.leafId}:${event.continuation}`;
if (handledSquashEvents.has(eventKey)) return;

const generation = activityGeneration;
if (!isCurrentSquashEvent(event, generation)) return;

handledSquashEvents.add(eventKey);
scheduleAgentEndNudge(
"squashCompletionNudge",
() => isCurrentSquashEvent(event, generation),
);
}

/** Render the subagent identity and tool availability widget. */
function renderWidget(ctx: Pick<ExtensionContext, "ui">): void {
ctx.ui.setWidget(
Expand Down Expand Up @@ -198,39 +258,52 @@ export default function (pi: ExtensionAPI) {
recorder.sessionStart();
doneCalled = false;
userInputAfterAgentEnd = false;
clearNudgeTimer();
isAgentAborted = false;
isAgentActive = false;
userTookOver = false;
activeSessionContext = ctx;
handledSquashEvents.clear();
invalidateNudge();
const tools = pi.getAllTools();
toolNames = tools.map((t) => t.name).sort();

renderWidget(ctx);
});

pi.on("input", () => {
pi.on("input", (event): void => {
recorder.input();
// User typed something — they are in control, cancel any pending nudge.
// 任意输入都是新活动,保留普通 stop 原有的取消提醒语义。
userInputAfterAgentEnd = true;
clearNudgeTimer();
// Ignore the initial task message that starts an autonomous subagent.
// Only inputs after the first agent run has started count as user takeover.
if (!shouldMarkUserTookOver(agentStarted)) return;
invalidateNudge();
// extension 输入不是人工接管,不能把补偿提醒误判成用户已接手。
if (event.source === "extension" || !shouldMarkUserTookOver(agentStarted)) return;
userTookOver = true;
});

pi.on("before_agent_start", () => {
recorder.beforeAgentStart();
// Agent is about to generate — clear any pending nudge; the AI is active.
clearNudgeTimer();
isAgentActive = true;
invalidateNudge();
});

pi.on("agent_start", () => {
agentStarted = true;
recorder.agentStart();
// Agent has started a new generation cycle — clear any pending nudge.
isAgentActive = true;
isAgentAborted = false;
userInputAfterAgentEnd = false;
clearNudgeTimer();
invalidateNudge();
});

pi.on("agent_end", (event, ctx) => {
isAgentActive = false;
isAgentAborted = !shouldScheduleAgentEndNudge(event.messages)
&& event.messages?.some((message) =>
message.role === ASSISTANT_ROLE && message.stopReason === ABORTED_STOP_REASON
) === true;
activeSessionContext = ctx;
// auto-exit 已彻底移除:agent 必须主动调用 subagent_done 工具才能结束 session。
// 之前的 autoExit 短路会在 agent 正常结束 turn 时直接写 { type: "done" } 到
// .exit 文件,绕过 subagent_done 工具。这会让 workflow 系统(启用
Expand All @@ -249,6 +322,12 @@ export default function (pi: ExtensionAPI) {
}
});

pi.on("agent_settled", (event): void => {
if ((event as { aborted?: unknown }).aborted !== true) return;
isAgentAborted = true;
invalidateNudge();
});

pi.on("turn_start", (event) => {
recorder.turnStart((event as any).turnIndex);
});
Expand Down Expand Up @@ -290,10 +369,16 @@ export default function (pi: ExtensionAPI) {
});

pi.on("session_shutdown", (event) => {
clearNudgeTimer();
isAgentActive = false;
activeSessionContext = null;
invalidateNudge();
recorder.sessionShutdown((event as any).reason);
});

pi.events.on(SQUASH_COMPLETED_EVENT, (data): void => {
if (isSquashCompletedEvent(data)) scheduleSquashCompletionNudge(data);
});

// Toggle expand/collapse with Ctrl+J
pi.registerShortcut("ctrl+j", {
description: "Toggle subagent tools widget",
Expand Down Expand Up @@ -325,7 +410,7 @@ export default function (pi: ExtensionAPI) {
}

doneCalled = true;
clearNudgeTimer();
invalidateNudge();
recorder.callerPing();
const exitData = {
type: "ping" as const,
Expand Down Expand Up @@ -431,7 +516,7 @@ export default function (pi: ExtensionAPI) {
}

doneCalled = true;
clearNudgeTimer();
invalidateNudge();
recorder.subagentDone();

if (sessionFile) {
Expand Down
Loading
Loading