@xzzpig/pi-subagents 0.16.0 → 0.19.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 +233 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +34 -21
- package/docs/configuration.md +82 -7
- package/docs/extension-api.md +75 -8
- package/docs/missions.md +13 -13
- package/docs/models.md +7 -5
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +5 -5
- package/docs/tool-reference.md +98 -100
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +214 -162
- package/inspector-runner.mjs +1 -1
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +15 -9
- package/prompts/council.md +6 -3
- package/prompts/review-loop.md +1 -1
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +13 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
- package/skills/pi-subagents/references/execution-controls.md +72 -69
- package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
- package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +63 -54
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +132 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +7 -2
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +10 -4
- package/src/extension/fanout-child.ts +20 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +168 -206
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +39 -11
- package/src/extension/schemas.ts +47 -138
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +146 -0
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +26 -16
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +60 -95
- package/src/runs/background/async-job-tracker.ts +91 -56
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +98 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +20 -6
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +16 -4
- package/src/runs/background/runner-aliases.ts +54 -16
- package/src/runs/background/runner-child-launch.ts +4 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +111 -288
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +111 -139
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +715 -258
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +37 -16
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +144 -8
- package/src/runs/shared/child-tool-plan.ts +38 -116
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +5 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +35 -10
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +12 -0
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +4 -1
- package/src/runs/shared/pi-spawn.ts +1 -3
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +36 -9
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/model-info.ts +9 -0
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +73 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +18 -3
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +17 -246
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +4 -5
- package/src/tui/fleet-status.ts +38 -8
- package/src/tui/fleet.ts +21 -6
- package/src/tui/render.ts +166 -71
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +47 -12
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +13 -5
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +16 -16
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +12 -6
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +225 -59
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import packageJson from "../../package.json" with { type: "json" };
|
|
5
|
+
import { writeAtomicJson } from "../shared/atomic-json.ts";
|
|
6
|
+
import { getAgentDir } from "../shared/utils.ts";
|
|
7
|
+
|
|
8
|
+
// major.minor.patch as one comparable number; undefined for anything else.
|
|
9
|
+
const versionNumber = (version: unknown) => typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version)
|
|
10
|
+
? version.split(".").reduce((total, part) => total * 1e6 + Number(part), 0)
|
|
11
|
+
: undefined;
|
|
12
|
+
|
|
13
|
+
export async function showUpgradeNotice(
|
|
14
|
+
ctx: { hasUI: boolean; ui: { notify(message: string, type: "info"): void } },
|
|
15
|
+
stateDir = path.join(getAgentDir(), "pi-subagents"),
|
|
16
|
+
changelogPath = fileURLToPath(new URL("../../CHANGELOG.md", import.meta.url)),
|
|
17
|
+
version = packageJson.version,
|
|
18
|
+
): Promise<void> {
|
|
19
|
+
if (!ctx.hasUI) return;
|
|
20
|
+
const statePath = path.join(stateDir, "last-seen-version.json");
|
|
21
|
+
const lastSeen = await fs.promises.readFile(statePath, "utf-8").then((raw) => JSON.parse(raw).version).catch(() => undefined);
|
|
22
|
+
const previous = versionNumber(lastSeen);
|
|
23
|
+
const current = versionNumber(version);
|
|
24
|
+
if (current === undefined || previous === current) return;
|
|
25
|
+
writeAtomicJson(statePath, { version });
|
|
26
|
+
if (previous === undefined || previous > current) return;
|
|
27
|
+
|
|
28
|
+
const bullets = (await fs.promises.readFile(changelogPath, "utf-8")).split(/^## /m).flatMap((section) => {
|
|
29
|
+
const released = versionNumber(/^\[([^\]]+)\]/.exec(section)?.[1]);
|
|
30
|
+
if (released === undefined || released <= previous || released > current) return [];
|
|
31
|
+
const highlights = section.split(/^### /m).find((part) => part.startsWith("Highlights")) ?? "";
|
|
32
|
+
return (highlights.match(/^- .*/gm) ?? []).map((bullet) => bullet.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim());
|
|
33
|
+
});
|
|
34
|
+
ctx.ui.notify([
|
|
35
|
+
`pi-subagents updated from ${lastSeen} to ${version}`,
|
|
36
|
+
...bullets.slice(0, 5),
|
|
37
|
+
...(bullets.length > 5 ? [`...and ${bullets.length - 5} more`] : []),
|
|
38
|
+
"Changelog: https://github.com/nicobailon/pi-subagents/blob/main/CHANGELOG.md",
|
|
39
|
+
].join("\n"), "info");
|
|
40
|
+
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { openGhosttyInspector, type GhosttyRunner } from "./actions.ts";
|
|
2
2
|
import type { InspectorPlugin } from "../types.ts";
|
|
3
3
|
|
|
4
|
+
/** 独立 Ghostty.app 的 bundle id (作者 Mitchell Hashimoto)。 */
|
|
5
|
+
const GHOSTTY_BUNDLE_ID = "com.mitchellh.ghostty";
|
|
6
|
+
|
|
4
7
|
export interface GhosttyPluginDeps {
|
|
5
8
|
platform?: NodeJS.Platform;
|
|
6
9
|
runner?: GhosttyRunner;
|
|
@@ -10,7 +13,16 @@ export function createGhosttyInspectorPlugin(deps: GhosttyPluginDeps = {}): Insp
|
|
|
10
13
|
const platform = deps.platform ?? process.platform;
|
|
11
14
|
return {
|
|
12
15
|
name: "ghostty",
|
|
13
|
-
available: (context) =>
|
|
16
|
+
available: (context) => {
|
|
17
|
+
// cmux 内嵌 Ghostty 内核, 也会把 TERM_PROGRAM 设成 "ghostty"。仅凭环境变量会让 plugin
|
|
18
|
+
// 在 cmux 下误接管, 随后 osascript 连不上真正的 Ghostty 应用而抛 -1728/-2741。
|
|
19
|
+
if (platform !== "darwin") return false;
|
|
20
|
+
if (context.env.TERM_PROGRAM?.toLowerCase() !== "ghostty") return false;
|
|
21
|
+
// macOS GUI 应用启动子进程时注入 __CFBundleIdentifier, 标识当前终端宿主 app。
|
|
22
|
+
// cmux 的 bundle id 是 com.cmuxterm.app, 而非 Ghostty; 即便系统同时装了独立 Ghostty,
|
|
23
|
+
// 也能据此判定当前终端不是 Ghostty, 避免误连独立 Ghostty 的窗口。
|
|
24
|
+
return context.env.__CFBundleIdentifier?.trim() === GHOSTTY_BUNDLE_ID;
|
|
25
|
+
},
|
|
14
26
|
owns: () => false,
|
|
15
27
|
open: (context, launch, params) => openGhosttyInspector(context, launch, params, deps.runner),
|
|
16
28
|
};
|
|
@@ -1,8 +1,75 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { INSPECTOR_REGISTER_EVENT, type InspectorRegistrationRequest } from "../api/inspectors.ts";
|
|
1
3
|
import { createHerdrInspectorPlugin } from "./herdr/plugin.ts";
|
|
2
4
|
import { createGhosttyInspectorPlugin } from "./ghostty/plugin.ts";
|
|
3
5
|
import type { InspectorPlugin } from "./types.ts";
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
type InspectorOwner = Pick<ExtensionAPI, "events">;
|
|
8
|
+
// Keyed by event bus: a runtime that claims a registration can be replaced by a duplicate
|
|
9
|
+
// pi-subagents runtime on the same bus, and the registration must survive that takeover.
|
|
10
|
+
const registries = new WeakMap<InspectorOwner["events"], { plugins: Map<string, InspectorPlugin>; owners: number }>();
|
|
11
|
+
|
|
12
|
+
/** Built-ins retain host preference; external providers follow registration order. */
|
|
13
|
+
export function getInspectorPlugins(pi: InspectorOwner): readonly InspectorPlugin[] {
|
|
14
|
+
return [createHerdrInspectorPlugin(), createGhosttyInspectorPlugin(), ...(registries.get(pi.events)?.plugins.values() ?? [])];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Registrations live while any owner runtime listens on this bus; child runtimes use their own bus. */
|
|
18
|
+
export function registerInspectorEventListener(pi: InspectorOwner): () => void {
|
|
19
|
+
let registry = registries.get(pi.events);
|
|
20
|
+
if (!registry) {
|
|
21
|
+
registry = { plugins: new Map(), owners: 0 };
|
|
22
|
+
registries.set(pi.events, registry);
|
|
23
|
+
}
|
|
24
|
+
registry.owners += 1;
|
|
25
|
+
const { plugins } = registry;
|
|
26
|
+
const builtinNames = new Set([createHerdrInspectorPlugin().name, createGhosttyInspectorPlugin().name]);
|
|
27
|
+
/* oxlint-disable anti-slop/no-runtime-typeof -- This listener validates the untyped event-bus boundary, including callable provider methods. */
|
|
28
|
+
const unsubscribe = pi.events.on(INSPECTOR_REGISTER_EVENT, (rawRequest) => {
|
|
29
|
+
if (!rawRequest || typeof rawRequest !== "object" || Array.isArray(rawRequest)) return;
|
|
30
|
+
// SAFETY: The envelope is an object; its version and plugin are validated below before storing callbacks.
|
|
31
|
+
const request = rawRequest as Partial<InspectorRegistrationRequest>;
|
|
32
|
+
if (request.result !== undefined) return;
|
|
33
|
+
try {
|
|
34
|
+
if (request.version !== 1) throw new Error(`Unsupported inspector registration version '${String(request.version)}'.`);
|
|
35
|
+
const plugin = request.plugin;
|
|
36
|
+
if (!plugin || typeof plugin !== "object" || Array.isArray(plugin)) throw new Error("Inspector plugin must be an object.");
|
|
37
|
+
const name = plugin.name;
|
|
38
|
+
if (typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)) {
|
|
39
|
+
throw new Error("Inspector plugin name must contain 1–128 letters, digits, dots, underscores, or hyphens and start with a letter or digit.");
|
|
40
|
+
}
|
|
41
|
+
if (builtinNames.has(name) || plugins.has(name)) throw new Error(`Inspector plugin '${name}' is already registered.`);
|
|
42
|
+
for (const method of ["available", "owns", "open"] as const) {
|
|
43
|
+
if (typeof plugin[method] !== "function") throw new Error(`Inspector plugin '${name}' requires ${method}().`);
|
|
44
|
+
}
|
|
45
|
+
for (const method of ["status", "close"] as const) {
|
|
46
|
+
if (plugin[method] !== undefined && typeof plugin[method] !== "function") throw new Error(`Inspector plugin '${name}' ${method} must be a function when provided.`);
|
|
47
|
+
}
|
|
48
|
+
plugins.set(name, plugin);
|
|
49
|
+
let disposed = false;
|
|
50
|
+
request.result = {
|
|
51
|
+
ok: true,
|
|
52
|
+
registration: {
|
|
53
|
+
dispose() {
|
|
54
|
+
if (disposed) return;
|
|
55
|
+
disposed = true;
|
|
56
|
+
plugins.delete(name);
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
} catch (error) {
|
|
61
|
+
request.result = { ok: false, error: error instanceof Error ? error : new Error(String(error)) };
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
/* oxlint-enable anti-slop/no-runtime-typeof */
|
|
65
|
+
let closed = false;
|
|
66
|
+
return () => {
|
|
67
|
+
if (closed) return;
|
|
68
|
+
closed = true;
|
|
69
|
+
unsubscribe();
|
|
70
|
+
registry.owners -= 1;
|
|
71
|
+
if (registry.owners > 0) return;
|
|
72
|
+
plugins.clear();
|
|
73
|
+
if (registries.get(pi.events) === registry) registries.delete(pi.events);
|
|
74
|
+
};
|
|
8
75
|
}
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
} from "../shared/types.ts";
|
|
6
6
|
import { previewDisplayText, sanitizeDisplayText } from "../shared/display-text.ts";
|
|
7
7
|
|
|
8
|
+
export const HERDR_FOREGROUND_CONTROL_CHANGED_EVENT = "pi-subagents:herdr:foreground-control-changed";
|
|
8
9
|
const DEFAULT_SOURCE = "pi-subagents:herdr";
|
|
9
10
|
const DEFAULT_TTL_MS = 120_000;
|
|
10
11
|
const DEFAULT_REFRESH_MS = 45_000;
|
|
@@ -29,6 +30,8 @@ export interface HerdrStatusRun {
|
|
|
29
30
|
id: string;
|
|
30
31
|
agent?: string;
|
|
31
32
|
agents?: string[];
|
|
33
|
+
/** A workflow owns busy state but is not itself a child agent. */
|
|
34
|
+
coordinator?: true;
|
|
32
35
|
/** Explicit launch/workflow label only; raw prompts never enter pane metadata. */
|
|
33
36
|
taskLabel?: string;
|
|
34
37
|
needsAttention?: boolean;
|
|
@@ -100,10 +103,17 @@ function workflowTaskLabel(data: Record<string, unknown>): string | undefined {
|
|
|
100
103
|
function startedRun(data: unknown): HerdrStatusRun | undefined {
|
|
101
104
|
if (!isRecord(data) || typeof data.id !== "string" || !data.id) return undefined;
|
|
102
105
|
const taskLabel = workflowTaskLabel(data);
|
|
106
|
+
// The workflow coordinator itself is not a running leaf: it starts with its
|
|
107
|
+
// own `agent: "workflow"` identity, but its actual leaves each publish their
|
|
108
|
+
// own start event separately. Counting the coordinator here would double it.
|
|
109
|
+
const isWorkflowCoordinator = data.mode === "workflow";
|
|
103
110
|
return {
|
|
104
111
|
id: data.id,
|
|
105
|
-
...(
|
|
106
|
-
...(
|
|
112
|
+
...(isWorkflowCoordinator ? { coordinator: true as const } : {}),
|
|
113
|
+
...(!isWorkflowCoordinator && typeof data.agent === "string" ? { agent: data.agent } : {}),
|
|
114
|
+
...(isWorkflowCoordinator
|
|
115
|
+
? { agents: [] }
|
|
116
|
+
: Array.isArray(data.agents) && data.agents.every((agent) => typeof agent === "string") ? { agents: data.agents as string[] } : {}),
|
|
107
117
|
...(taskLabel ? { taskLabel } : {}),
|
|
108
118
|
};
|
|
109
119
|
}
|
|
@@ -150,7 +160,10 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
|
|
|
150
160
|
let refreshTimer: ReturnType<typeof setInterval> | undefined;
|
|
151
161
|
|
|
152
162
|
const activeAgentNames = (): string[] => [...new Set([...runs.values()].flatMap((run) => run.agents?.length ? run.agents : run.agent ? [run.agent] : []))];
|
|
153
|
-
|
|
163
|
+
// Preserve the minimum count for ordinary runs with incomplete status;
|
|
164
|
+
// only an empty workflow coordinator contributes zero child agents.
|
|
165
|
+
const activeSubagentCount = (): number => [...runs.values()].reduce((total, run) =>
|
|
166
|
+
total + (run.coordinator && !run.agents?.length ? 0 : Math.max(1, run.agents?.length ?? (run.agent ? 1 : 0))), 0);
|
|
154
167
|
const activeTaskLabel = (): string | undefined => [...runs.values()].reverse().find((run) => run.taskLabel)?.taskLabel;
|
|
155
168
|
|
|
156
169
|
const label = (includeAttention = false): string => {
|
|
@@ -340,6 +353,9 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
|
|
|
340
353
|
};
|
|
341
354
|
|
|
342
355
|
if (enabled) {
|
|
356
|
+
subscribe(HERDR_FOREGROUND_CONTROL_CHANGED_EVENT, () => {
|
|
357
|
+
if (rootSession && options.getRuns) refresh();
|
|
358
|
+
});
|
|
343
359
|
subscribe(SUBAGENT_ASYNC_STARTED_EVENT, (data) => {
|
|
344
360
|
if (!rootSession) return;
|
|
345
361
|
const run = startedRun(data);
|
|
@@ -90,6 +90,8 @@ interface ResolveIntercomBridgeInput {
|
|
|
90
90
|
agentDir?: string;
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
// Inside a child, callers pass the child's intercom route instead of its session
|
|
94
|
+
// name: the name is a readable label and need not be unique.
|
|
93
95
|
export function resolveIntercomSessionTarget(sessionName: string | undefined, sessionId: string, intercomSessionId = process.env[PI_INTERCOM_SESSION_ID_ENV]): string {
|
|
94
96
|
const trimmedName = sessionName?.trim();
|
|
95
97
|
if (trimmedName) return trimmedName;
|
|
@@ -8,6 +8,7 @@ import type { ChildSupervisorMetadata } from "../runs/shared/child-runtime-confi
|
|
|
8
8
|
import { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type ControlEvent, type IntercomEventBus, type SubagentState } from "../shared/types.ts";
|
|
9
9
|
import { writeAtomicJson } from "../shared/atomic-json.ts";
|
|
10
10
|
import { shouldUseNativeFsWatch } from "../shared/watch-strategy.ts";
|
|
11
|
+
import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
|
|
11
12
|
import {
|
|
12
13
|
SUPERVISOR_REQUEST_MESSAGE_TYPE,
|
|
13
14
|
SUPERVISOR_REPLY_ENTRY_TYPE,
|
|
@@ -259,6 +260,7 @@ export function registerNativeSupervisorClient(pi: ExtensionAPI, metadata: Child
|
|
|
259
260
|
if (!metadata || hasTool(pi, "contact_supervisor")) return;
|
|
260
261
|
const tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {
|
|
261
262
|
name: "contact_supervisor",
|
|
263
|
+
...MODEL_ONLY_TOOL,
|
|
262
264
|
label: "Contact Supervisor",
|
|
263
265
|
description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
|
|
264
266
|
parameters: ContactSupervisorParamsSchema,
|
|
@@ -288,13 +290,18 @@ function parseRequestFile(file: string, channelDir: string): PendingSupervisorRe
|
|
|
288
290
|
}
|
|
289
291
|
}
|
|
290
292
|
|
|
291
|
-
function
|
|
293
|
+
function isMissingSupervisorDirectory(error: unknown, platform: NodeJS.Platform): boolean {
|
|
294
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
295
|
+
return code === "ENOENT" || (platform === "win32" && code === "UNKNOWN");
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function listRequestFiles(channelDirs: string[] | undefined, platform: NodeJS.Platform): Array<{ channelDir: string; file: string }> {
|
|
292
299
|
if (!channelDirs) {
|
|
293
300
|
try {
|
|
294
301
|
channelDirs = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true })
|
|
295
302
|
.filter(entry => entry.isDirectory()).map(entry => path.join(SUPERVISOR_CHANNEL_ROOT, entry.name));
|
|
296
303
|
} catch (error) {
|
|
297
|
-
if ((error
|
|
304
|
+
if (isMissingSupervisorDirectory(error, platform)) return [];
|
|
298
305
|
throw error;
|
|
299
306
|
}
|
|
300
307
|
}
|
|
@@ -314,11 +321,11 @@ function listRequestFiles(channelDirs?: string[]): Array<{ channelDir: string; f
|
|
|
314
321
|
return files;
|
|
315
322
|
}
|
|
316
323
|
|
|
317
|
-
function readDirectoryEntries(dir: string): fs.Dirent[] | undefined {
|
|
324
|
+
function readDirectoryEntries(dir: string, platform: NodeJS.Platform): fs.Dirent[] | undefined {
|
|
318
325
|
try {
|
|
319
326
|
return fs.readdirSync(dir, { withFileTypes: true });
|
|
320
327
|
} catch (error) {
|
|
321
|
-
if ((error
|
|
328
|
+
if (isMissingSupervisorDirectory(error, platform)) return [];
|
|
322
329
|
return undefined;
|
|
323
330
|
}
|
|
324
331
|
}
|
|
@@ -343,7 +350,7 @@ function removeEmptyDirectory(dir: string): boolean {
|
|
|
343
350
|
}
|
|
344
351
|
}
|
|
345
352
|
|
|
346
|
-
function removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number): boolean {
|
|
353
|
+
function removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number, platform: NodeJS.Platform): boolean {
|
|
347
354
|
const requestsDir = path.join(channelDir, REQUESTS_DIR);
|
|
348
355
|
const repliesDir = path.join(channelDir, REPLIES_DIR);
|
|
349
356
|
const newestKnownMtimeMs = Math.max(
|
|
@@ -353,9 +360,9 @@ function removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number): b
|
|
|
353
360
|
);
|
|
354
361
|
if (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS) return false;
|
|
355
362
|
|
|
356
|
-
const requestEntries = readDirectoryEntries(requestsDir);
|
|
363
|
+
const requestEntries = readDirectoryEntries(requestsDir, platform);
|
|
357
364
|
if (!requestEntries || requestEntries.length > 0) return false;
|
|
358
|
-
const replyEntries = readDirectoryEntries(repliesDir);
|
|
365
|
+
const replyEntries = readDirectoryEntries(repliesDir, platform);
|
|
359
366
|
if (!replyEntries || replyEntries.length > 0) return false;
|
|
360
367
|
|
|
361
368
|
if (!removeEmptyDirectory(requestsDir)) return false;
|
|
@@ -364,12 +371,12 @@ function removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number): b
|
|
|
364
371
|
return true;
|
|
365
372
|
}
|
|
366
373
|
|
|
367
|
-
function cleanupStaleEmptySupervisorChannels(nowMs = Date.now()): number {
|
|
374
|
+
function cleanupStaleEmptySupervisorChannels(nowMs = Date.now(), platform: NodeJS.Platform = process.platform): number {
|
|
368
375
|
let channelEntries: fs.Dirent[];
|
|
369
376
|
try {
|
|
370
377
|
channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
|
|
371
378
|
} catch (error) {
|
|
372
|
-
if ((error
|
|
379
|
+
if (isMissingSupervisorDirectory(error, platform)) return 0;
|
|
373
380
|
throw error;
|
|
374
381
|
}
|
|
375
382
|
|
|
@@ -377,7 +384,7 @@ function cleanupStaleEmptySupervisorChannels(nowMs = Date.now()): number {
|
|
|
377
384
|
for (const entry of channelEntries) {
|
|
378
385
|
if (!entry.isDirectory()) continue;
|
|
379
386
|
try {
|
|
380
|
-
if (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs)) removed++;
|
|
387
|
+
if (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs, platform)) removed++;
|
|
381
388
|
} catch {
|
|
382
389
|
// Cleanup is opportunistic; active writers can race with us and will be picked up by a later pass.
|
|
383
390
|
}
|
|
@@ -482,7 +489,9 @@ function refreshPendingRequests(pending: Map<string, PendingSupervisorRequest>,
|
|
|
482
489
|
|
|
483
490
|
function formatPendingLine(request: PendingSupervisorRequest): string {
|
|
484
491
|
const replyHint = request.expectsReply ? ` Reply: ${supervisorReplyHint(request.id)}` : "";
|
|
485
|
-
|
|
492
|
+
const header = `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.${replyHint}`;
|
|
493
|
+
// The request notice can be missed; pending is the parent's only way to read the question again.
|
|
494
|
+
return request.message ? `${header}\n ${request.message.replace(/\n/g, "\n ")}` : header;
|
|
486
495
|
}
|
|
487
496
|
|
|
488
497
|
function requestVisibleText(request: PendingSupervisorRequest): string {
|
|
@@ -578,6 +587,7 @@ function publicPendingRequests(pending: Map<string, PendingSupervisorRequest>):
|
|
|
578
587
|
function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver, discover: () => void, runState: (request: SupervisorRequest) => SubagentState): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
|
|
579
588
|
return {
|
|
580
589
|
name: NATIVE_SUPERVISOR_TOOL_NAME,
|
|
590
|
+
...MODEL_ONLY_TOOL,
|
|
581
591
|
label: "Subagent Supervisor",
|
|
582
592
|
description: "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
|
|
583
593
|
parameters: IntercomParamsSchema,
|
|
@@ -709,7 +719,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
709
719
|
if (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;
|
|
710
720
|
lastStaleCleanupAt = nowMs;
|
|
711
721
|
try {
|
|
712
|
-
cleanupStaleEmptySupervisorChannels(nowMs);
|
|
722
|
+
cleanupStaleEmptySupervisorChannels(nowMs, platform);
|
|
713
723
|
} catch {
|
|
714
724
|
// Supervisor delivery must not fail because best-effort temp cleanup failed.
|
|
715
725
|
}
|
|
@@ -721,7 +731,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
721
731
|
refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
|
|
722
732
|
const now = Date.now();
|
|
723
733
|
const channels = deps.getChannelDirs?.();
|
|
724
|
-
for (const { channelDir, file } of listRequestFiles(channels?.dirs)) {
|
|
734
|
+
for (const { channelDir, file } of listRequestFiles(channels?.dirs, platform)) {
|
|
725
735
|
if (seenFiles.has(file)) continue;
|
|
726
736
|
const request = parseRequestFile(file, channelDir);
|
|
727
737
|
if (!request || !requestMatchesOwner(request, state)) continue;
|
|
@@ -781,7 +791,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
781
791
|
if (poller) return;
|
|
782
792
|
poller = timers.setInterval(() => {
|
|
783
793
|
poll();
|
|
784
|
-
if (!useNativeWatcher() &&
|
|
794
|
+
if (!useNativeWatcher() && !hasTransportDemand()) {
|
|
785
795
|
if (poller) timers.clearInterval(poller);
|
|
786
796
|
poller = undefined;
|
|
787
797
|
}
|
|
@@ -816,7 +826,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
816
826
|
try {
|
|
817
827
|
channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
|
|
818
828
|
} catch (error) {
|
|
819
|
-
if ((error
|
|
829
|
+
if (isMissingSupervisorDirectory(error, platform)) return;
|
|
820
830
|
startPolling();
|
|
821
831
|
return;
|
|
822
832
|
}
|
|
@@ -848,7 +858,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
848
858
|
let files: string[];
|
|
849
859
|
try { files = fs.readdirSync(path.join(channelDir, REQUESTS_DIR)); }
|
|
850
860
|
catch (error) {
|
|
851
|
-
if ((error
|
|
861
|
+
if (isMissingSupervisorDirectory(error, platform)) return [];
|
|
852
862
|
throw error;
|
|
853
863
|
}
|
|
854
864
|
const now = Date.now();
|
|
@@ -31,6 +31,7 @@ export function resolveSubagentResultStatus(input: {
|
|
|
31
31
|
if (input.detached) return "detached";
|
|
32
32
|
if (input.stopped || input.state === "stopped") return "stopped";
|
|
33
33
|
if (input.interrupted || input.state === "paused") return "paused";
|
|
34
|
+
if (input.state === "running" || input.state === "queued") return "running";
|
|
34
35
|
if (input.success === true) return "completed";
|
|
35
36
|
if (isUnexplainedProcessSignal(input) && input.exitCode !== 0) return "stopped";
|
|
36
37
|
if (input.success === false) return "failed";
|
|
@@ -42,6 +43,7 @@ export function resolveSubagentResultStatus(input: {
|
|
|
42
43
|
|
|
43
44
|
function countStatuses(children: SubagentResultIntercomChild[]): Record<SubagentResultStatus, number> {
|
|
44
45
|
const counts: Record<SubagentResultStatus, number> = {
|
|
46
|
+
running: 0,
|
|
45
47
|
completed: 0,
|
|
46
48
|
failed: 0,
|
|
47
49
|
paused: 0,
|
|
@@ -56,6 +58,7 @@ function countStatuses(children: SubagentResultIntercomChild[]): Record<Subagent
|
|
|
56
58
|
|
|
57
59
|
function formatStatusCounts(counts: Record<SubagentResultStatus, number>): string {
|
|
58
60
|
const parts = [
|
|
61
|
+
counts.running ? `${counts.running} running` : undefined,
|
|
59
62
|
counts.completed ? `${counts.completed} completed` : undefined,
|
|
60
63
|
counts.failed ? `${counts.failed} failed` : undefined,
|
|
61
64
|
counts.stopped ? `${counts.stopped} stopped` : undefined,
|
|
@@ -85,6 +88,7 @@ function resolveGroupedStatus(children: SubagentResultIntercomChild[]): Subagent
|
|
|
85
88
|
if (counts.failed > 0) return "failed";
|
|
86
89
|
if (counts.stopped > 0) return "stopped";
|
|
87
90
|
if (counts.paused > 0) return "paused";
|
|
91
|
+
if (counts.running > 0) return "running";
|
|
88
92
|
if (counts.completed > 0) return "completed";
|
|
89
93
|
if (counts.detached > 0) return "detached";
|
|
90
94
|
return "failed";
|
|
@@ -6,6 +6,7 @@ import { TEMP_ROOT_DIR, type ActiveAsyncCapacitySnapshot, type AsyncStatus } fro
|
|
|
6
6
|
import { readStatus } from "../../shared/utils.ts";
|
|
7
7
|
import { checkPidLiveness, type PidLiveness } from "./stale-run-reconciler.ts";
|
|
8
8
|
import { readProcessTerminal } from "./process-terminal.ts";
|
|
9
|
+
import { isTerminalAsyncState as terminalState, readWorkflowChildProcessEvidence } from "./workflow-terminal-proof.ts";
|
|
9
10
|
|
|
10
11
|
export const ACTIVE_ASYNC_CAPACITY_DIR = path.join(TEMP_ROOT_DIR, "session-active-async-capacity");
|
|
11
12
|
export const DEFAULT_ABANDONED_SLOT_RELEASE_AFTER_MS = 20 * 60 * 1000;
|
|
@@ -209,10 +210,6 @@ function appendAbandonedReleaseEvent(asyncDir: string, owner: ActiveAsyncCapacit
|
|
|
209
210
|
}
|
|
210
211
|
}
|
|
211
212
|
|
|
212
|
-
function terminalState(state: AsyncStatus["state"]): boolean {
|
|
213
|
-
return state !== "queued" && state !== "running" && state !== "paused";
|
|
214
|
-
}
|
|
215
|
-
|
|
216
213
|
function runnerReleaseVerdict(owner: ActiveAsyncCapacityOwner, status: AsyncStatus | null, options: CapacityOptions): ActiveAsyncCapacityReleaseVerdict {
|
|
217
214
|
if (!status) return { state: "retained", reason: "status file is missing or unreadable" };
|
|
218
215
|
if (!owner.runnerProcessInstanceId) return { state: "retained", reason: "runner process identity has not been recorded" };
|
|
@@ -269,27 +266,8 @@ function workflowReleaseVerdict(owner: ActiveAsyncCapacityOwner, status: AsyncSt
|
|
|
269
266
|
if (status.mode !== "workflow") return { state: "retained", reason: `status mode is ${status.mode}, not workflow` };
|
|
270
267
|
if (!terminalState(status.state)) return { state: "retained", reason: `workflow is still ${status.state}` };
|
|
271
268
|
if (liveWorkflowRunIds.has(owner.runId)) return { state: "retained", reason: "workflow controller is still live" };
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
if (typeof step.async !== "boolean") return { state: "retained", reason: `workflow child ${label} is missing async classification` };
|
|
275
|
-
if (!step.async) continue;
|
|
276
|
-
if (!step.runId) return { state: "retained", reason: `async workflow child ${label} is missing run id` };
|
|
277
|
-
const childDir = path.join(path.dirname(owner.asyncDir), step.runId);
|
|
278
|
-
if (!fs.existsSync(childDir)) return { state: "retained", reason: `async workflow child ${label} directory is missing` };
|
|
279
|
-
const childStatus = readStatus(childDir);
|
|
280
|
-
if (!childStatus) return { state: "retained", reason: `async workflow child ${label} status is missing or unreadable` };
|
|
281
|
-
if (!terminalState(childStatus.state)) return { state: "retained", reason: `async workflow child ${label} is still ${childStatus.state}` };
|
|
282
|
-
if (!childStatus.processTerminal?.runnerProcessInstanceId) return { state: "retained", reason: `async workflow child ${label} has no runner process identity` };
|
|
283
|
-
if (childStatus.processTerminal.state === "not-started"
|
|
284
|
-
&& childStatus.processTerminal.runId === step.runId
|
|
285
|
-
&& typeof childStatus.error === "string"
|
|
286
|
-
&& childStatus.error) continue;
|
|
287
|
-
const proof = readProcessTerminal(childDir, {
|
|
288
|
-
runId: step.runId,
|
|
289
|
-
runnerProcessInstanceId: childStatus.processTerminal.runnerProcessInstanceId,
|
|
290
|
-
});
|
|
291
|
-
if (proof?.state !== "observed" || proof.runId !== step.runId) return { state: "retained", reason: `async workflow child ${label} process-terminal proof is ${proof?.state ?? "missing"}` };
|
|
292
|
-
}
|
|
269
|
+
const evidence = readWorkflowChildProcessEvidence(owner.asyncDir, status.steps);
|
|
270
|
+
if (evidence.state !== "observed") return { state: "retained", reason: evidence.reason };
|
|
293
271
|
return { state: "releasable", reason: "workflow is terminal, controller is gone, and async children have observed proof" };
|
|
294
272
|
}
|
|
295
273
|
|