@xzzpig/pi-subagents 0.1.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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
5
|
+
import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { Type } from "typebox";
|
|
7
|
+
import {
|
|
8
|
+
SUBAGENT_CHILD_AGENT_ENV,
|
|
9
|
+
SUBAGENT_CHILD_INDEX_ENV,
|
|
10
|
+
SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV,
|
|
11
|
+
SUBAGENT_ORCHESTRATOR_TARGET_ENV,
|
|
12
|
+
SUBAGENT_RUN_ID_ENV,
|
|
13
|
+
SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV,
|
|
14
|
+
} from "../runs/shared/pi-args.ts";
|
|
15
|
+
import { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type IntercomEventBus, type SubagentState } from "../shared/types.ts";
|
|
16
|
+
import { writeAtomicJson } from "../shared/atomic-json.ts";
|
|
17
|
+
|
|
18
|
+
const SUPERVISOR_CHANNEL_ROOT = path.join(TEMP_ROOT_DIR, "supervisor-channels");
|
|
19
|
+
const REQUESTS_DIR = "requests";
|
|
20
|
+
const REPLIES_DIR = "replies";
|
|
21
|
+
export const NATIVE_SUPERVISOR_TOOL_NAME = "subagent_supervisor";
|
|
22
|
+
const MAX_MESSAGE_BYTES = 64 * 1024;
|
|
23
|
+
const DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1000;
|
|
24
|
+
const CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500);
|
|
25
|
+
const STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1000;
|
|
26
|
+
const STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1000;
|
|
27
|
+
|
|
28
|
+
type SupervisorReason = "need_decision" | "interview_request" | "progress_update";
|
|
29
|
+
|
|
30
|
+
interface SupervisorRequest {
|
|
31
|
+
type: "subagent.supervisor.request";
|
|
32
|
+
id: string;
|
|
33
|
+
createdAt: number;
|
|
34
|
+
expiresAt?: number;
|
|
35
|
+
reason: SupervisorReason;
|
|
36
|
+
message: string;
|
|
37
|
+
expectsReply: boolean;
|
|
38
|
+
orchestratorTarget?: string;
|
|
39
|
+
orchestratorSessionId?: string;
|
|
40
|
+
runId: string;
|
|
41
|
+
agent: string;
|
|
42
|
+
childIndex: number;
|
|
43
|
+
childTarget?: string;
|
|
44
|
+
interview?: unknown;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface PendingSupervisorRequest extends SupervisorRequest {
|
|
48
|
+
channelDir: string;
|
|
49
|
+
requestFile: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface SupervisorReply {
|
|
53
|
+
type: "subagent.supervisor.reply";
|
|
54
|
+
requestId: string;
|
|
55
|
+
createdAt: number;
|
|
56
|
+
message: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface ContactSupervisorParams {
|
|
60
|
+
reason: SupervisorReason;
|
|
61
|
+
message?: string;
|
|
62
|
+
interview?: unknown;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface IntercomParams {
|
|
66
|
+
action: "list" | "send" | "ask" | "reply" | "pending" | "status";
|
|
67
|
+
to?: string;
|
|
68
|
+
message?: string;
|
|
69
|
+
replyTo?: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const ContactSupervisorParamsSchema = Type.Object({
|
|
73
|
+
reason: Type.String({ enum: ["need_decision", "interview_request", "progress_update"] }),
|
|
74
|
+
message: Type.Optional(Type.String()),
|
|
75
|
+
interview: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true })),
|
|
76
|
+
}, { additionalProperties: false });
|
|
77
|
+
|
|
78
|
+
const IntercomParamsSchema = Type.Object({
|
|
79
|
+
action: Type.String({ enum: ["list", "send", "ask", "reply", "pending", "status"] }),
|
|
80
|
+
to: Type.Optional(Type.String()),
|
|
81
|
+
message: Type.Optional(Type.String()),
|
|
82
|
+
replyTo: Type.Optional(Type.String()),
|
|
83
|
+
}, { additionalProperties: false });
|
|
84
|
+
|
|
85
|
+
function safeSegment(value: string): string {
|
|
86
|
+
return value.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "unknown";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function resolveSupervisorChannelDir(runId: string, agent: string, childIndex: number): string {
|
|
90
|
+
return path.join(SUPERVISOR_CHANNEL_ROOT, `${safeSegment(runId)}-${safeSegment(agent)}-${childIndex}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function ensureSupervisorChannelDir(channelDir: string): void {
|
|
94
|
+
fs.mkdirSync(path.join(channelDir, REQUESTS_DIR), { recursive: true, mode: 0o700 });
|
|
95
|
+
fs.mkdirSync(path.join(channelDir, REPLIES_DIR), { recursive: true, mode: 0o700 });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function requestPath(channelDir: string, requestId: string): string {
|
|
99
|
+
return path.join(channelDir, REQUESTS_DIR, `${safeSegment(requestId)}.json`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function replyPath(channelDir: string, requestId: string): string {
|
|
103
|
+
return path.join(channelDir, REPLIES_DIR, `${safeSegment(requestId)}.json`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function readTextEnv(name: string): string | undefined {
|
|
107
|
+
const value = process.env[name]?.trim();
|
|
108
|
+
return value ? value : undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function readChildMetadata(): {
|
|
112
|
+
channelDir: string;
|
|
113
|
+
runId: string;
|
|
114
|
+
agent: string;
|
|
115
|
+
childIndex: number;
|
|
116
|
+
orchestratorTarget?: string;
|
|
117
|
+
orchestratorSessionId?: string;
|
|
118
|
+
childTarget?: string;
|
|
119
|
+
} | undefined {
|
|
120
|
+
const channelDir = readTextEnv(SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV);
|
|
121
|
+
const runId = readTextEnv(SUBAGENT_RUN_ID_ENV);
|
|
122
|
+
const agent = readTextEnv(SUBAGENT_CHILD_AGENT_ENV);
|
|
123
|
+
const rawIndex = readTextEnv(SUBAGENT_CHILD_INDEX_ENV);
|
|
124
|
+
const orchestratorSessionId = readTextEnv(SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV);
|
|
125
|
+
if (!channelDir || !runId || !agent || !orchestratorSessionId || rawIndex === undefined || !/^\d+$/.test(rawIndex)) return undefined;
|
|
126
|
+
return {
|
|
127
|
+
channelDir,
|
|
128
|
+
runId,
|
|
129
|
+
agent,
|
|
130
|
+
childIndex: Number(rawIndex),
|
|
131
|
+
orchestratorTarget: readTextEnv(SUBAGENT_ORCHESTRATOR_TARGET_ENV),
|
|
132
|
+
orchestratorSessionId,
|
|
133
|
+
childTarget: readTextEnv("PI_SUBAGENT_INTERCOM_SESSION_NAME"),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function reasonHeading(reason: SupervisorReason): string {
|
|
138
|
+
if (reason === "interview_request") return "Subagent requests a structured supervisor interview.";
|
|
139
|
+
if (reason === "progress_update") return "Subagent progress update.";
|
|
140
|
+
return "Subagent needs a supervisor decision.";
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function formatChildMessage(input: {
|
|
144
|
+
reason: SupervisorReason;
|
|
145
|
+
message?: string;
|
|
146
|
+
interview?: unknown;
|
|
147
|
+
runId: string;
|
|
148
|
+
agent: string;
|
|
149
|
+
childIndex: number;
|
|
150
|
+
childTarget?: string;
|
|
151
|
+
}): string {
|
|
152
|
+
const lines = [
|
|
153
|
+
reasonHeading(input.reason),
|
|
154
|
+
`Run: ${input.runId}`,
|
|
155
|
+
`Agent: ${input.agent}`,
|
|
156
|
+
`Child index: ${input.childIndex}`,
|
|
157
|
+
];
|
|
158
|
+
if (input.childTarget) lines.push(`Child intercom target: ${input.childTarget}`);
|
|
159
|
+
lines.push("");
|
|
160
|
+
if (input.message?.trim()) lines.push(input.message.trim());
|
|
161
|
+
if (input.reason === "interview_request") {
|
|
162
|
+
lines.push(
|
|
163
|
+
"",
|
|
164
|
+
"Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape.",
|
|
165
|
+
);
|
|
166
|
+
if (input.interview !== undefined) lines.push(JSON.stringify(input.interview, null, "\t"));
|
|
167
|
+
}
|
|
168
|
+
return lines.join("\n").trimEnd();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function parseStructuredReply(message: string): { value?: unknown; error?: string } {
|
|
172
|
+
const trimmed = message.trim();
|
|
173
|
+
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)?.[1]?.trim();
|
|
174
|
+
try {
|
|
175
|
+
return { value: JSON.parse(fenced ?? trimmed) };
|
|
176
|
+
} catch (error) {
|
|
177
|
+
return { error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function askTimeoutMs(): number {
|
|
182
|
+
const parsed = Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);
|
|
183
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function delay(ms: number, signal?: AbortSignal): Promise<void> {
|
|
187
|
+
return new Promise((resolve, reject) => {
|
|
188
|
+
if (signal?.aborted) {
|
|
189
|
+
reject(new Error("Supervisor request cancelled."));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
193
|
+
const cleanup = () => {
|
|
194
|
+
if (timer) clearTimeout(timer);
|
|
195
|
+
signal?.removeEventListener("abort", onAbort);
|
|
196
|
+
};
|
|
197
|
+
const onAbort = () => {
|
|
198
|
+
cleanup();
|
|
199
|
+
reject(new Error("Supervisor request cancelled."));
|
|
200
|
+
};
|
|
201
|
+
timer = setTimeout(() => {
|
|
202
|
+
cleanup();
|
|
203
|
+
resolve();
|
|
204
|
+
}, ms);
|
|
205
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function waitForReply(channelDir: string, requestId: string, deadline: number, signal?: AbortSignal): Promise<SupervisorReply> {
|
|
210
|
+
const file = replyPath(channelDir, requestId);
|
|
211
|
+
while (Date.now() <= deadline) {
|
|
212
|
+
if (signal?.aborted) throw new Error("Supervisor request cancelled.");
|
|
213
|
+
if (fs.existsSync(file)) {
|
|
214
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf-8")) as Partial<SupervisorReply>;
|
|
215
|
+
if (parsed.type === "subagent.supervisor.reply" && parsed.requestId === requestId && typeof parsed.message === "string") {
|
|
216
|
+
return parsed as SupervisorReply;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
await delay(250, signal);
|
|
220
|
+
}
|
|
221
|
+
throw new Error("Timed out waiting for supervisor reply.");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function sendSupervisorRequest(params: ContactSupervisorParams, signal?: AbortSignal): Promise<AgentToolResult<Record<string, unknown>>> {
|
|
225
|
+
const metadata = readChildMetadata();
|
|
226
|
+
if (!metadata) throw new Error("Native supervisor channel is not available for this subagent.");
|
|
227
|
+
if (params.reason !== "progress_update" && !params.message?.trim() && params.reason !== "interview_request") {
|
|
228
|
+
throw new Error("message is required for supervisor decisions.");
|
|
229
|
+
}
|
|
230
|
+
ensureSupervisorChannelDir(metadata.channelDir);
|
|
231
|
+
const requestId = randomUUID();
|
|
232
|
+
const expectsReply = params.reason !== "progress_update";
|
|
233
|
+
const createdAt = Date.now();
|
|
234
|
+
const replyDeadline = createdAt + askTimeoutMs();
|
|
235
|
+
const expiresAt = expectsReply ? replyDeadline : undefined;
|
|
236
|
+
const message = formatChildMessage({ ...metadata, reason: params.reason, message: params.message, interview: params.interview });
|
|
237
|
+
const request: SupervisorRequest = {
|
|
238
|
+
type: "subagent.supervisor.request",
|
|
239
|
+
id: requestId,
|
|
240
|
+
createdAt,
|
|
241
|
+
...(expiresAt !== undefined ? { expiresAt } : {}),
|
|
242
|
+
reason: params.reason,
|
|
243
|
+
message,
|
|
244
|
+
expectsReply,
|
|
245
|
+
...(metadata.orchestratorTarget ? { orchestratorTarget: metadata.orchestratorTarget } : {}),
|
|
246
|
+
...(metadata.orchestratorSessionId ? { orchestratorSessionId: metadata.orchestratorSessionId } : {}),
|
|
247
|
+
runId: metadata.runId,
|
|
248
|
+
agent: metadata.agent,
|
|
249
|
+
childIndex: metadata.childIndex,
|
|
250
|
+
...(metadata.childTarget ? { childTarget: metadata.childTarget } : {}),
|
|
251
|
+
...(params.interview !== undefined ? { interview: params.interview } : {}),
|
|
252
|
+
};
|
|
253
|
+
const serialized = JSON.stringify(request, null, "\t");
|
|
254
|
+
if (Buffer.byteLength(serialized, "utf-8") > MAX_MESSAGE_BYTES) throw new Error("Supervisor request is too large.");
|
|
255
|
+
writeAtomicJson(requestPath(metadata.channelDir, requestId), request);
|
|
256
|
+
|
|
257
|
+
if (!expectsReply) {
|
|
258
|
+
return {
|
|
259
|
+
content: [{ type: "text", text: "Supervisor progress update queued." }],
|
|
260
|
+
details: { delivered: true, requestId, reason: params.reason },
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
try {
|
|
265
|
+
const reply = await waitForReply(metadata.channelDir, requestId, replyDeadline, signal);
|
|
266
|
+
const details: Record<string, unknown> = { requestId, reason: params.reason };
|
|
267
|
+
if (params.reason === "interview_request") {
|
|
268
|
+
const structured = parseStructuredReply(reply.message);
|
|
269
|
+
if (structured.error) details.structuredReplyParseError = structured.error;
|
|
270
|
+
else details.structuredReply = structured.value;
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
content: [{ type: "text", text: `**Reply from supervisor:**\n${reply.message}` }],
|
|
274
|
+
details,
|
|
275
|
+
};
|
|
276
|
+
} catch (error) {
|
|
277
|
+
removeRequestFile(requestPath(metadata.channelDir, requestId));
|
|
278
|
+
throw error;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function hasTool(pi: ExtensionAPI, name: string): boolean {
|
|
283
|
+
try {
|
|
284
|
+
return pi.getAllTools?.().some((tool: { name?: unknown }) => tool.name === name) === true;
|
|
285
|
+
} catch {
|
|
286
|
+
return false;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function registerNativeSupervisorClient(pi: ExtensionAPI, options: { includeIntercomFallback?: boolean } = {}): void {
|
|
291
|
+
if (!readChildMetadata()) return;
|
|
292
|
+
const includeIntercomFallback = options.includeIntercomFallback !== false;
|
|
293
|
+
if (!hasTool(pi, "contact_supervisor")) {
|
|
294
|
+
const tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {
|
|
295
|
+
name: "contact_supervisor",
|
|
296
|
+
label: "Contact Supervisor",
|
|
297
|
+
description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
|
|
298
|
+
parameters: ContactSupervisorParamsSchema,
|
|
299
|
+
execute(_id, params, signal) {
|
|
300
|
+
return sendSupervisorRequest(params as ContactSupervisorParams, signal);
|
|
301
|
+
},
|
|
302
|
+
};
|
|
303
|
+
pi.registerTool(tool);
|
|
304
|
+
}
|
|
305
|
+
if (includeIntercomFallback && !hasTool(pi, "intercom")) {
|
|
306
|
+
const tool: ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> = {
|
|
307
|
+
name: "intercom",
|
|
308
|
+
label: "Intercom",
|
|
309
|
+
description: "Native supervisor-channel intercom fallback for subagents. Prefer contact_supervisor when available.",
|
|
310
|
+
parameters: IntercomParamsSchema,
|
|
311
|
+
async execute(_id, params, signal) {
|
|
312
|
+
const action = (params as IntercomParams).action;
|
|
313
|
+
if (action === "status") return { content: [{ type: "text", text: "Native supervisor channel is active." }], details: { active: true } };
|
|
314
|
+
if (action === "list") return { content: [{ type: "text", text: "Supervisor session available through contact_supervisor." }], details: { sessions: [] } };
|
|
315
|
+
if (action === "send") return sendSupervisorRequest({ reason: "progress_update", message: (params as IntercomParams).message ?? "" }, signal);
|
|
316
|
+
if (action === "ask") return sendSupervisorRequest({ reason: "need_decision", message: (params as IntercomParams).message ?? "" }, signal);
|
|
317
|
+
throw new Error("Native child intercom supports status, list, send, and ask. Use parent intercom reply from the supervisor session.");
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
pi.registerTool(tool);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function parseRequestFile(file: string, channelDir: string): PendingSupervisorRequest | undefined {
|
|
325
|
+
try {
|
|
326
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf-8")) as Partial<SupervisorRequest>;
|
|
327
|
+
if (parsed.type !== "subagent.supervisor.request") return undefined;
|
|
328
|
+
if (typeof parsed.id !== "string" || !parsed.id) return undefined;
|
|
329
|
+
if (parsed.reason !== "need_decision" && parsed.reason !== "interview_request" && parsed.reason !== "progress_update") return undefined;
|
|
330
|
+
if (typeof parsed.message !== "string" || !parsed.message) return undefined;
|
|
331
|
+
if (typeof parsed.runId !== "string" || typeof parsed.agent !== "string" || typeof parsed.childIndex !== "number") return undefined;
|
|
332
|
+
return { ...parsed as SupervisorRequest, channelDir, requestFile: file };
|
|
333
|
+
} catch {
|
|
334
|
+
return undefined;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function listRequestFiles(): Array<{ channelDir: string; file: string }> {
|
|
339
|
+
let channelEntries: fs.Dirent[];
|
|
340
|
+
try {
|
|
341
|
+
channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
|
|
342
|
+
} catch (error) {
|
|
343
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
346
|
+
const files: Array<{ channelDir: string; file: string }> = [];
|
|
347
|
+
for (const entry of channelEntries) {
|
|
348
|
+
if (!entry.isDirectory()) continue;
|
|
349
|
+
const channelDir = path.join(SUPERVISOR_CHANNEL_ROOT, entry.name);
|
|
350
|
+
const requestsDir = path.join(channelDir, REQUESTS_DIR);
|
|
351
|
+
let requestEntries: fs.Dirent[];
|
|
352
|
+
try {
|
|
353
|
+
requestEntries = fs.readdirSync(requestsDir, { withFileTypes: true });
|
|
354
|
+
} catch {
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
for (const requestEntry of requestEntries) {
|
|
358
|
+
if (requestEntry.isFile() && requestEntry.name.endsWith(".json")) files.push({ channelDir, file: path.join(requestsDir, requestEntry.name) });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return files;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function readDirectoryEntries(dir: string): fs.Dirent[] | undefined {
|
|
365
|
+
try {
|
|
366
|
+
return fs.readdirSync(dir, { withFileTypes: true });
|
|
367
|
+
} catch (error) {
|
|
368
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
369
|
+
return undefined;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function directoryMtimeMs(dir: string): number {
|
|
374
|
+
try {
|
|
375
|
+
return fs.statSync(dir).mtimeMs;
|
|
376
|
+
} catch {
|
|
377
|
+
return 0;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function removeEmptyDirectory(dir: string): boolean {
|
|
382
|
+
try {
|
|
383
|
+
fs.rmdirSync(dir);
|
|
384
|
+
return true;
|
|
385
|
+
} catch (error) {
|
|
386
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
387
|
+
if (code === "ENOENT") return true;
|
|
388
|
+
if (code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM" || code === "EBUSY") return false;
|
|
389
|
+
throw error;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number): boolean {
|
|
394
|
+
const requestsDir = path.join(channelDir, REQUESTS_DIR);
|
|
395
|
+
const repliesDir = path.join(channelDir, REPLIES_DIR);
|
|
396
|
+
const newestKnownMtimeMs = Math.max(
|
|
397
|
+
directoryMtimeMs(channelDir),
|
|
398
|
+
directoryMtimeMs(requestsDir),
|
|
399
|
+
directoryMtimeMs(repliesDir),
|
|
400
|
+
);
|
|
401
|
+
if (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS) return false;
|
|
402
|
+
|
|
403
|
+
const requestEntries = readDirectoryEntries(requestsDir);
|
|
404
|
+
if (!requestEntries || requestEntries.length > 0) return false;
|
|
405
|
+
const replyEntries = readDirectoryEntries(repliesDir);
|
|
406
|
+
if (!replyEntries || replyEntries.length > 0) return false;
|
|
407
|
+
|
|
408
|
+
if (!removeEmptyDirectory(requestsDir)) return false;
|
|
409
|
+
if (!removeEmptyDirectory(repliesDir)) return false;
|
|
410
|
+
if (!removeEmptyDirectory(channelDir)) return false;
|
|
411
|
+
return true;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function cleanupStaleEmptySupervisorChannels(nowMs = Date.now()): number {
|
|
415
|
+
let channelEntries: fs.Dirent[];
|
|
416
|
+
try {
|
|
417
|
+
channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
|
|
418
|
+
} catch (error) {
|
|
419
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return 0;
|
|
420
|
+
throw error;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
let removed = 0;
|
|
424
|
+
for (const entry of channelEntries) {
|
|
425
|
+
if (!entry.isDirectory()) continue;
|
|
426
|
+
try {
|
|
427
|
+
if (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs)) removed++;
|
|
428
|
+
} catch {
|
|
429
|
+
// Cleanup is opportunistic; active writers can race with us and will be picked up by a later pass.
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return removed;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function currentContextSessionId(state: Pick<SubagentState, "currentSessionId">, ctx: ExtensionContext): string | undefined {
|
|
436
|
+
try {
|
|
437
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
438
|
+
if (sessionId) return sessionId;
|
|
439
|
+
} catch {
|
|
440
|
+
// Fall through to the last known identity.
|
|
441
|
+
}
|
|
442
|
+
return state.currentSessionId ?? undefined;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function requestMatchesContext(request: SupervisorRequest, state: Pick<SubagentState, "currentSessionId">, ctx: ExtensionContext): boolean {
|
|
446
|
+
const currentSessionId = currentContextSessionId(state, ctx);
|
|
447
|
+
return Boolean(currentSessionId && request.orchestratorSessionId === currentSessionId);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function rememberedForegroundChild(request: SupervisorRequest, state: SubagentState) {
|
|
451
|
+
const run = state.foregroundRuns?.get(request.runId);
|
|
452
|
+
const child = run?.children.find((candidate) => candidate.index === request.childIndex && candidate.agent === request.agent)
|
|
453
|
+
?? run?.children[request.childIndex];
|
|
454
|
+
return run && child ? { run, child } : undefined;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function markForegroundSupervisorAttention(request: SupervisorRequest, state: SubagentState): void {
|
|
458
|
+
const remembered = rememberedForegroundChild(request, state);
|
|
459
|
+
if (!remembered || remembered.child.status !== "detached") return;
|
|
460
|
+
const updatedAt = Date.now();
|
|
461
|
+
remembered.run.updatedAt = updatedAt;
|
|
462
|
+
remembered.child.activityState = "needs_attention";
|
|
463
|
+
remembered.child.lastActivityAt = request.createdAt;
|
|
464
|
+
remembered.child.currentTool = "contact_supervisor";
|
|
465
|
+
remembered.child.currentToolStartedAt = request.createdAt;
|
|
466
|
+
remembered.child.updatedAt = updatedAt;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function clearForegroundSupervisorAttention(request: SupervisorRequest, pending: Map<string, PendingSupervisorRequest>, state: SubagentState): void {
|
|
470
|
+
if ([...pending.values()].some((candidate) =>
|
|
471
|
+
candidate.expectsReply
|
|
472
|
+
&& candidate.runId === request.runId
|
|
473
|
+
&& candidate.agent === request.agent
|
|
474
|
+
&& candidate.childIndex === request.childIndex
|
|
475
|
+
)) return;
|
|
476
|
+
const remembered = rememberedForegroundChild(request, state);
|
|
477
|
+
if (!remembered || remembered.child.status !== "detached" || remembered.child.currentTool !== "contact_supervisor") return;
|
|
478
|
+
const updatedAt = Date.now();
|
|
479
|
+
remembered.run.updatedAt = updatedAt;
|
|
480
|
+
remembered.child.activityState = undefined;
|
|
481
|
+
remembered.child.lastActivityAt = updatedAt;
|
|
482
|
+
remembered.child.currentTool = undefined;
|
|
483
|
+
remembered.child.currentToolStartedAt = undefined;
|
|
484
|
+
remembered.child.updatedAt = updatedAt;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function removeRequestFile(file: string): void {
|
|
488
|
+
try {
|
|
489
|
+
fs.rmSync(file, { force: true });
|
|
490
|
+
} catch {
|
|
491
|
+
// Request cleanup is best-effort; reply files and timeout errors remain authoritative.
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
type SupervisorRequestLifecycle = "pending" | "resolved" | "expired" | "inactive" | "missing" | "wrong-session";
|
|
496
|
+
|
|
497
|
+
function requestExpiresAt(request: SupervisorRequest, now: number): number {
|
|
498
|
+
const expiresAt = (request as { expiresAt?: unknown }).expiresAt;
|
|
499
|
+
if (typeof expiresAt === "number" && Number.isFinite(expiresAt)) return expiresAt;
|
|
500
|
+
return Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs() : now;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function requestRunInactive(request: SupervisorRequest, state: SubagentState): boolean {
|
|
504
|
+
if (state.foregroundControls.has(request.runId)) return false;
|
|
505
|
+
const foreground = rememberedForegroundChild(request, state);
|
|
506
|
+
if (foreground) return foreground.child.status !== "detached";
|
|
507
|
+
|
|
508
|
+
const asyncJob = state.asyncJobs.get(request.runId);
|
|
509
|
+
if (!asyncJob) return false;
|
|
510
|
+
if (asyncJob.status === "complete" || asyncJob.status === "failed" || asyncJob.status === "paused") return true;
|
|
511
|
+
const stepStatus = asyncJob.steps?.[request.childIndex]?.status;
|
|
512
|
+
return stepStatus === "complete" || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "paused";
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function requestLifecycle(request: PendingSupervisorRequest, state: SubagentState, ctx: ExtensionContext | undefined, now: number): SupervisorRequestLifecycle {
|
|
516
|
+
if (ctx && !requestMatchesContext(request, state, ctx)) return "wrong-session";
|
|
517
|
+
if (!fs.existsSync(request.requestFile)) return "missing";
|
|
518
|
+
if (request.expectsReply && fs.existsSync(replyPath(request.channelDir, request.id))) return "resolved";
|
|
519
|
+
if (request.expectsReply && now > requestExpiresAt(request, now)) return "expired";
|
|
520
|
+
if (request.expectsReply && requestRunInactive(request, state)) return "inactive";
|
|
521
|
+
return "pending";
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function cleanupRequestLifecycle(request: PendingSupervisorRequest, lifecycle: SupervisorRequestLifecycle): void {
|
|
525
|
+
if (lifecycle === "resolved" || lifecycle === "expired" || lifecycle === "inactive") removeRequestFile(request.requestFile);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function refreshPendingRequests(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, ctx: ExtensionContext | undefined): void {
|
|
529
|
+
const now = Date.now();
|
|
530
|
+
for (const request of pending.values()) {
|
|
531
|
+
const lifecycle = requestLifecycle(request, state, ctx, now);
|
|
532
|
+
if (lifecycle === "pending") continue;
|
|
533
|
+
pending.delete(request.id);
|
|
534
|
+
cleanupRequestLifecycle(request, lifecycle);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function formatPendingLine(request: PendingSupervisorRequest): string {
|
|
539
|
+
const replyHint = request.expectsReply ? ` Reply: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: "reply", replyTo: "${request.id}", message: "..." })` : "";
|
|
540
|
+
return `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.${replyHint}`;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function requestVisibleText(request: PendingSupervisorRequest): string {
|
|
544
|
+
const lines = [request.message];
|
|
545
|
+
if (request.expectsReply) {
|
|
546
|
+
lines.push("", `Reply with: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: "reply", replyTo: "${request.id}", message: "..." })`);
|
|
547
|
+
}
|
|
548
|
+
return lines.join("\n");
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function writeReply(request: PendingSupervisorRequest, message: string): void {
|
|
552
|
+
if (!message.trim()) throw new Error("message is required for supervisor replies.");
|
|
553
|
+
const reply: SupervisorReply = {
|
|
554
|
+
type: "subagent.supervisor.reply",
|
|
555
|
+
requestId: request.id,
|
|
556
|
+
createdAt: Date.now(),
|
|
557
|
+
message: message.trim(),
|
|
558
|
+
};
|
|
559
|
+
writeAtomicJson(replyPath(request.channelDir, request.id), reply);
|
|
560
|
+
removeRequestFile(request.requestFile);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function resolvePendingRequest(pending: Map<string, PendingSupervisorRequest>, params: IntercomParams): PendingSupervisorRequest {
|
|
564
|
+
if (params.replyTo) {
|
|
565
|
+
const request = pending.get(params.replyTo);
|
|
566
|
+
if (!request) throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'.`);
|
|
567
|
+
return request;
|
|
568
|
+
}
|
|
569
|
+
const requests = [...pending.values()].filter((request) => request.expectsReply);
|
|
570
|
+
if (params.to) {
|
|
571
|
+
const normalizedTo = params.to.toLowerCase();
|
|
572
|
+
const matches = requests.filter((request) =>
|
|
573
|
+
request.id.toLowerCase().startsWith(normalizedTo)
|
|
574
|
+
|| request.agent.toLowerCase() === normalizedTo
|
|
575
|
+
|| request.childTarget?.toLowerCase() === normalizedTo,
|
|
576
|
+
);
|
|
577
|
+
if (matches.length === 1) return matches[0]!;
|
|
578
|
+
if (matches.length > 1) throw new Error(`Multiple pending supervisor requests match '${params.to}'. Use replyTo.`);
|
|
579
|
+
}
|
|
580
|
+
if (requests.length === 1) return requests[0]!;
|
|
581
|
+
if (requests.length === 0) throw new Error("No pending supervisor requests need a reply.");
|
|
582
|
+
throw new Error("Multiple pending supervisor requests need replies. Use replyTo.");
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function publicPendingRequests(pending: Map<string, PendingSupervisorRequest>): Array<Record<string, unknown>> {
|
|
586
|
+
return [...pending.values()].map((request) => ({
|
|
587
|
+
id: request.id,
|
|
588
|
+
runId: request.runId,
|
|
589
|
+
agent: request.agent,
|
|
590
|
+
childIndex: request.childIndex,
|
|
591
|
+
reason: request.reason,
|
|
592
|
+
expectsReply: request.expectsReply,
|
|
593
|
+
}));
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function buildParentIntercomTool(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, name = "intercom"): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
|
|
597
|
+
return {
|
|
598
|
+
name,
|
|
599
|
+
label: name === "intercom" ? "Intercom" : "Subagent Supervisor",
|
|
600
|
+
description: name === "intercom"
|
|
601
|
+
? "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests."
|
|
602
|
+
: "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
|
|
603
|
+
parameters: IntercomParamsSchema,
|
|
604
|
+
async execute(_id, params) {
|
|
605
|
+
refreshPendingRequests(pending, state, state.lastUiContext ?? undefined);
|
|
606
|
+
const input = params as IntercomParams;
|
|
607
|
+
if (input.action === "status") {
|
|
608
|
+
return { content: [{ type: "text", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };
|
|
609
|
+
}
|
|
610
|
+
if (input.action === "pending" || input.action === "list") {
|
|
611
|
+
const lines = [...pending.values()].filter((request) => request.expectsReply).map(formatPendingLine);
|
|
612
|
+
return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No pending supervisor requests." }], details: { pending: publicPendingRequests(pending) } };
|
|
613
|
+
}
|
|
614
|
+
if (input.action === "reply") {
|
|
615
|
+
const request = resolvePendingRequest(pending, input);
|
|
616
|
+
writeReply(request, input.message ?? "");
|
|
617
|
+
pending.delete(request.id);
|
|
618
|
+
clearForegroundSupervisorAttention(request, pending, state);
|
|
619
|
+
return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
|
|
620
|
+
}
|
|
621
|
+
if (input.action === "send" || input.action === "ask") {
|
|
622
|
+
throw new Error("Native pi-subagents intercom currently handles supervisor replies. Child agents initiate asks with contact_supervisor.");
|
|
623
|
+
}
|
|
624
|
+
throw new Error(`Unsupported intercom action: ${input.action}`);
|
|
625
|
+
},
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState): { start: () => void; dispose: () => void; pending: Map<string, PendingSupervisorRequest> } {
|
|
630
|
+
const pending = new Map<string, PendingSupervisorRequest>();
|
|
631
|
+
const seenFiles = new Set<string>();
|
|
632
|
+
let poller: ReturnType<typeof setInterval> | undefined;
|
|
633
|
+
let lastStaleCleanupAt = 0;
|
|
634
|
+
|
|
635
|
+
const registerParentTools = (): void => {
|
|
636
|
+
if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentIntercomTool(pending, state, NATIVE_SUPERVISOR_TOOL_NAME));
|
|
637
|
+
if (!hasTool(pi, "intercom")) pi.registerTool(buildParentIntercomTool(pending, state));
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
const cleanupStaleChannelsIfDue = (): void => {
|
|
641
|
+
const nowMs = Date.now();
|
|
642
|
+
if (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;
|
|
643
|
+
lastStaleCleanupAt = nowMs;
|
|
644
|
+
try {
|
|
645
|
+
cleanupStaleEmptySupervisorChannels(nowMs);
|
|
646
|
+
} catch {
|
|
647
|
+
// Supervisor delivery must not fail because best-effort temp cleanup failed.
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
const poll = (): void => {
|
|
652
|
+
cleanupStaleChannelsIfDue();
|
|
653
|
+
const ctx = state.lastUiContext;
|
|
654
|
+
if (!ctx) return;
|
|
655
|
+
refreshPendingRequests(pending, state, ctx);
|
|
656
|
+
const now = Date.now();
|
|
657
|
+
for (const { channelDir, file } of listRequestFiles()) {
|
|
658
|
+
if (seenFiles.has(file)) continue;
|
|
659
|
+
const request = parseRequestFile(file, channelDir);
|
|
660
|
+
if (!request || !requestMatchesContext(request, state, ctx)) continue;
|
|
661
|
+
const lifecycle = requestLifecycle(request, state, undefined, now);
|
|
662
|
+
if (lifecycle !== "pending") {
|
|
663
|
+
seenFiles.add(file);
|
|
664
|
+
cleanupRequestLifecycle(request, lifecycle);
|
|
665
|
+
continue;
|
|
666
|
+
}
|
|
667
|
+
seenFiles.add(file);
|
|
668
|
+
if (request.expectsReply) {
|
|
669
|
+
pending.set(request.id, request);
|
|
670
|
+
markForegroundSupervisorAttention(request, state);
|
|
671
|
+
}
|
|
672
|
+
else {
|
|
673
|
+
removeRequestFile(request.requestFile);
|
|
674
|
+
}
|
|
675
|
+
pi.sendMessage({
|
|
676
|
+
customType: "subagent_supervisor_request",
|
|
677
|
+
content: requestVisibleText(request),
|
|
678
|
+
display: true,
|
|
679
|
+
details: {
|
|
680
|
+
id: request.id,
|
|
681
|
+
reason: request.reason,
|
|
682
|
+
expectsReply: request.expectsReply,
|
|
683
|
+
runId: request.runId,
|
|
684
|
+
agent: request.agent,
|
|
685
|
+
childIndex: request.childIndex,
|
|
686
|
+
},
|
|
687
|
+
}, { triggerTurn: true });
|
|
688
|
+
if (request.expectsReply) {
|
|
689
|
+
(pi as { events?: IntercomEventBus }).events?.emit(INTERCOM_DETACH_REQUEST_EVENT, {
|
|
690
|
+
requestId: request.id,
|
|
691
|
+
runId: request.runId,
|
|
692
|
+
agent: request.agent,
|
|
693
|
+
childIndex: request.childIndex,
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
};
|
|
698
|
+
|
|
699
|
+
return {
|
|
700
|
+
start: () => {
|
|
701
|
+
if (poller) return;
|
|
702
|
+
registerParentTools();
|
|
703
|
+
poll();
|
|
704
|
+
poller = setInterval(poll, CHANNEL_POLL_MS);
|
|
705
|
+
poller.unref?.();
|
|
706
|
+
},
|
|
707
|
+
dispose: () => {
|
|
708
|
+
if (poller) clearInterval(poller);
|
|
709
|
+
poller = undefined;
|
|
710
|
+
pending.clear();
|
|
711
|
+
seenFiles.clear();
|
|
712
|
+
},
|
|
713
|
+
pending,
|
|
714
|
+
};
|
|
715
|
+
}
|