@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,330 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SUBAGENT_ASYNC_COMPLETE_EVENT,
|
|
3
|
+
SUBAGENT_ASYNC_STARTED_EVENT,
|
|
4
|
+
SUBAGENT_CONTROL_EVENT,
|
|
5
|
+
} from "../shared/types.ts";
|
|
6
|
+
|
|
7
|
+
const DEFAULT_SOURCE = "pi-subagents:herdr";
|
|
8
|
+
const DEFAULT_TTL_MS = 120_000;
|
|
9
|
+
const DEFAULT_REFRESH_MS = 45_000;
|
|
10
|
+
|
|
11
|
+
let metadataReportSeq = Date.now() * 1000;
|
|
12
|
+
|
|
13
|
+
function nextMetadataReportSeq(): number {
|
|
14
|
+
metadataReportSeq = Math.max(metadataReportSeq + 1, Date.now() * 1000);
|
|
15
|
+
return metadataReportSeq;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface HerdrStatusBridgeEvents {
|
|
19
|
+
on(event: string, handler: (data: unknown) => void): (() => void) | void;
|
|
20
|
+
emit(event: string, data: unknown): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface HerdrStatusRun {
|
|
24
|
+
id: string;
|
|
25
|
+
agent?: string;
|
|
26
|
+
agents?: string[];
|
|
27
|
+
needsAttention?: boolean;
|
|
28
|
+
attentionLabel?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface HerdrStatusBridgeOptions {
|
|
32
|
+
events: HerdrStatusBridgeEvents;
|
|
33
|
+
env?: Record<string, string | undefined>;
|
|
34
|
+
/** Current authoritative active-run projection, used before TTL refresh. */
|
|
35
|
+
getRuns?: () => Iterable<HerdrStatusRun>;
|
|
36
|
+
runHerdr: (args: readonly string[]) => void | Promise<void>;
|
|
37
|
+
ttlMs?: number;
|
|
38
|
+
refreshMs?: number;
|
|
39
|
+
timers?: {
|
|
40
|
+
setInterval: typeof setInterval;
|
|
41
|
+
clearInterval: typeof clearInterval;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface HerdrStatusBridge {
|
|
46
|
+
/**
|
|
47
|
+
* Binds the pane owner. Only the root interactive session may publish pane
|
|
48
|
+
* metadata: headless parents (print/json), non-UI harnesses, and child
|
|
49
|
+
* runtimes must never fight the pane's lifecycle authority over display
|
|
50
|
+
* state. Also re-syncs runs that survived a reload/resume.
|
|
51
|
+
*/
|
|
52
|
+
sessionStarted(input: { hasUI: boolean; runs: Iterable<HerdrStatusRun> }): void;
|
|
53
|
+
agentStarted(): void;
|
|
54
|
+
flush(): Promise<void>;
|
|
55
|
+
dispose(): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
59
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function startedRun(data: unknown): HerdrStatusRun | undefined {
|
|
63
|
+
if (!isRecord(data) || typeof data.id !== "string" || !data.id) return undefined;
|
|
64
|
+
return {
|
|
65
|
+
id: data.id,
|
|
66
|
+
...(typeof data.agent === "string" ? { agent: data.agent } : {}),
|
|
67
|
+
...(Array.isArray(data.agents) && data.agents.every((agent) => typeof agent === "string") ? { agents: data.agents as string[] } : {}),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function completedRunId(data: unknown): string | undefined {
|
|
72
|
+
if (!isRecord(data)) return undefined;
|
|
73
|
+
const id = typeof data.runId === "string" ? data.runId : data.id;
|
|
74
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function attentionNotice(data: unknown): { runId: string; label: string } | undefined {
|
|
78
|
+
if (!isRecord(data) || data.source !== "async" || !isRecord(data.event)) return undefined;
|
|
79
|
+
if (data.event.type !== "needs_attention" || typeof data.event.runId !== "string" || !data.event.runId) return undefined;
|
|
80
|
+
const label = typeof data.noticeText === "string" && data.noticeText
|
|
81
|
+
? data.noticeText
|
|
82
|
+
: typeof data.event.message === "string" && data.event.message
|
|
83
|
+
? data.event.message
|
|
84
|
+
: "subagent needs attention";
|
|
85
|
+
return { runId: data.event.runId, label };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): HerdrStatusBridge {
|
|
89
|
+
const env = options.env ?? process.env;
|
|
90
|
+
const paneId = env.HERDR_PANE_ID;
|
|
91
|
+
const enabled = env.HERDR_ENV === "1" && typeof paneId === "string" && paneId.length > 0;
|
|
92
|
+
const runHerdr = options.runHerdr;
|
|
93
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
94
|
+
const refreshMs = options.refreshMs ?? DEFAULT_REFRESH_MS;
|
|
95
|
+
const timers = options.timers ?? { setInterval, clearInterval };
|
|
96
|
+
const runs = new Map<string, HerdrStatusRun>();
|
|
97
|
+
const attentionLabels = new Map<string, string>();
|
|
98
|
+
const acknowledgedAttention = new Set<string>();
|
|
99
|
+
const subscriptions: Array<() => void> = [];
|
|
100
|
+
let rootSession = false;
|
|
101
|
+
let published = false;
|
|
102
|
+
let busyRaised = false;
|
|
103
|
+
let busyLabel: string | undefined;
|
|
104
|
+
let blockedRaised = false;
|
|
105
|
+
let blockedLabel: string | undefined;
|
|
106
|
+
let disposed = false;
|
|
107
|
+
let pendingReport: readonly string[] | undefined;
|
|
108
|
+
let draining = false;
|
|
109
|
+
let drainPromise = Promise.resolve();
|
|
110
|
+
let refreshTimer: ReturnType<typeof setInterval> | undefined;
|
|
111
|
+
|
|
112
|
+
const label = (): string => {
|
|
113
|
+
const agents = [...new Set([...runs.values()].flatMap((run) => run.agents?.length ? run.agents : run.agent ? [run.agent] : []))];
|
|
114
|
+
const who = agents.length > 0
|
|
115
|
+
? ` (${agents.slice(0, 3).join(", ")}${agents.length > 3 ? ", …" : ""})`
|
|
116
|
+
: "";
|
|
117
|
+
return `⏳ ${runs.size} subagent${runs.size === 1 ? "" : "s"}${who}`;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const enqueue = (args: readonly string[]): void => {
|
|
121
|
+
pendingReport = args;
|
|
122
|
+
if (draining) return;
|
|
123
|
+
draining = true;
|
|
124
|
+
drainPromise = (async () => {
|
|
125
|
+
while (pendingReport) {
|
|
126
|
+
const next = pendingReport;
|
|
127
|
+
pendingReport = undefined;
|
|
128
|
+
try {
|
|
129
|
+
await runHerdr(next);
|
|
130
|
+
} catch {
|
|
131
|
+
// Herdr integration is best effort; a later state transition or TTL
|
|
132
|
+
// refresh retries with the newest desired snapshot.
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
})().finally(() => {
|
|
136
|
+
draining = false;
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const publish = (): void => {
|
|
141
|
+
if (!enabled || !rootSession || disposed || !paneId) return;
|
|
142
|
+
if (runs.size === 0 && !published) return;
|
|
143
|
+
const seq = String(nextMetadataReportSeq());
|
|
144
|
+
if (runs.size === 0) {
|
|
145
|
+
published = false;
|
|
146
|
+
enqueue([
|
|
147
|
+
"pane", "report-metadata", paneId,
|
|
148
|
+
"--source", DEFAULT_SOURCE,
|
|
149
|
+
"--agent", "pi",
|
|
150
|
+
"--applies-to-source", "herdr:pi",
|
|
151
|
+
"--clear-state-labels",
|
|
152
|
+
"--clear-token", "summary",
|
|
153
|
+
"--seq", seq,
|
|
154
|
+
]);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const text = label();
|
|
158
|
+
published = true;
|
|
159
|
+
enqueue([
|
|
160
|
+
"pane", "report-metadata", paneId,
|
|
161
|
+
"--source", DEFAULT_SOURCE,
|
|
162
|
+
"--agent", "pi",
|
|
163
|
+
"--applies-to-source", "herdr:pi",
|
|
164
|
+
"--state-label", `idle=${text}`,
|
|
165
|
+
"--state-label", `done=${text}`,
|
|
166
|
+
"--state-label", `working=${text}`,
|
|
167
|
+
"--token", `summary=${text}`,
|
|
168
|
+
"--ttl-ms", String(ttlMs),
|
|
169
|
+
"--seq", seq,
|
|
170
|
+
]);
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const syncRefreshTimer = (): void => {
|
|
174
|
+
if (runs.size > 0 && refreshMs > 0 && !refreshTimer) {
|
|
175
|
+
refreshTimer = timers.setInterval(() => refresh(), refreshMs);
|
|
176
|
+
refreshTimer.unref?.();
|
|
177
|
+
} else if ((runs.size === 0 || refreshMs <= 0) && refreshTimer) {
|
|
178
|
+
timers.clearInterval(refreshTimer);
|
|
179
|
+
refreshTimer = undefined;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const syncBusy = (): void => {
|
|
184
|
+
if (!enabled || !rootSession || disposed) return;
|
|
185
|
+
if (runs.size > 0) {
|
|
186
|
+
const text = label();
|
|
187
|
+
if (busyRaised && busyLabel === text) return;
|
|
188
|
+
if (busyRaised) options.events.emit("herdr:busy", { active: false });
|
|
189
|
+
busyRaised = true;
|
|
190
|
+
busyLabel = text;
|
|
191
|
+
options.events.emit("herdr:busy", { active: true, label: text });
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (busyRaised) {
|
|
195
|
+
busyRaised = false;
|
|
196
|
+
busyLabel = undefined;
|
|
197
|
+
options.events.emit("herdr:busy", { active: false });
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const syncBlocked = (): void => {
|
|
202
|
+
if (!enabled || !rootSession || disposed) return;
|
|
203
|
+
const nextLabel = [...attentionLabels.values()].at(-1);
|
|
204
|
+
if (nextLabel !== undefined) {
|
|
205
|
+
if (blockedRaised && blockedLabel === nextLabel) return;
|
|
206
|
+
// Herdr's sibling overlay contract is counted. Lower before changing
|
|
207
|
+
// the active label so this bridge continues to own exactly one count.
|
|
208
|
+
if (blockedRaised) options.events.emit("herdr:blocked", { active: false });
|
|
209
|
+
blockedRaised = true;
|
|
210
|
+
blockedLabel = nextLabel;
|
|
211
|
+
options.events.emit("herdr:blocked", { active: true, label: nextLabel });
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (blockedRaised) {
|
|
215
|
+
blockedRaised = false;
|
|
216
|
+
blockedLabel = undefined;
|
|
217
|
+
options.events.emit("herdr:blocked", { active: false });
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const clearAttention = (): void => {
|
|
222
|
+
attentionLabels.clear();
|
|
223
|
+
syncBlocked();
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const raiseAttention = (runId: string, labelText: string): void => {
|
|
227
|
+
if (!rootSession || attentionLabels.has(runId)) return;
|
|
228
|
+
acknowledgedAttention.delete(runId);
|
|
229
|
+
attentionLabels.set(runId, labelText);
|
|
230
|
+
syncBlocked();
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const replaceRuns = (nextRuns: Iterable<HerdrStatusRun>): void => {
|
|
234
|
+
const nextAttention = new Map<string, string>();
|
|
235
|
+
const activeIds = new Set<string>();
|
|
236
|
+
runs.clear();
|
|
237
|
+
for (const run of nextRuns) {
|
|
238
|
+
if (!run || typeof run.id !== "string" || !run.id) continue;
|
|
239
|
+
activeIds.add(run.id);
|
|
240
|
+
runs.set(run.id, { ...run });
|
|
241
|
+
if (!run.needsAttention) {
|
|
242
|
+
acknowledgedAttention.delete(run.id);
|
|
243
|
+
} else if (!acknowledgedAttention.has(run.id)) {
|
|
244
|
+
nextAttention.set(run.id, run.attentionLabel || attentionLabels.get(run.id) || "subagent needs attention");
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
for (const id of acknowledgedAttention) {
|
|
248
|
+
if (!activeIds.has(id)) acknowledgedAttention.delete(id);
|
|
249
|
+
}
|
|
250
|
+
attentionLabels.clear();
|
|
251
|
+
for (const [id, labelText] of nextAttention) attentionLabels.set(id, labelText);
|
|
252
|
+
syncBusy();
|
|
253
|
+
syncRefreshTimer();
|
|
254
|
+
syncBlocked();
|
|
255
|
+
publish();
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
const refresh = (): void => {
|
|
259
|
+
if (!options.getRuns) {
|
|
260
|
+
publish();
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
replaceRuns(options.getRuns());
|
|
265
|
+
} catch {
|
|
266
|
+
// Keep the last known active projection and retry on the next refresh.
|
|
267
|
+
publish();
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
const subscribe = (event: string, handler: (data: unknown) => void): void => {
|
|
272
|
+
const unsubscribe = options.events.on(event, handler);
|
|
273
|
+
if (typeof unsubscribe === "function") subscriptions.push(unsubscribe);
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
if (enabled) {
|
|
277
|
+
subscribe(SUBAGENT_ASYNC_STARTED_EVENT, (data) => {
|
|
278
|
+
if (!rootSession) return;
|
|
279
|
+
const run = startedRun(data);
|
|
280
|
+
if (!run) return;
|
|
281
|
+
acknowledgedAttention.delete(run.id);
|
|
282
|
+
runs.set(run.id, run);
|
|
283
|
+
syncBusy();
|
|
284
|
+
syncRefreshTimer();
|
|
285
|
+
publish();
|
|
286
|
+
});
|
|
287
|
+
subscribe(SUBAGENT_ASYNC_COMPLETE_EVENT, (data) => {
|
|
288
|
+
if (!rootSession) return;
|
|
289
|
+
const id = completedRunId(data);
|
|
290
|
+
if (!id || !runs.delete(id)) return;
|
|
291
|
+
acknowledgedAttention.delete(id);
|
|
292
|
+
if (attentionLabels.delete(id)) syncBlocked();
|
|
293
|
+
syncBusy();
|
|
294
|
+
syncRefreshTimer();
|
|
295
|
+
publish();
|
|
296
|
+
});
|
|
297
|
+
subscribe(SUBAGENT_CONTROL_EVENT, (data) => {
|
|
298
|
+
if (!rootSession) return;
|
|
299
|
+
const notice = attentionNotice(data);
|
|
300
|
+
if (!notice || !runs.has(notice.runId)) return;
|
|
301
|
+
raiseAttention(notice.runId, notice.label);
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return {
|
|
306
|
+
agentStarted() {
|
|
307
|
+
for (const id of attentionLabels.keys()) acknowledgedAttention.add(id);
|
|
308
|
+
clearAttention();
|
|
309
|
+
},
|
|
310
|
+
sessionStarted({ hasUI, runs: restoredRuns }) {
|
|
311
|
+
if (!enabled || disposed || hasUI !== true) return;
|
|
312
|
+
rootSession = true;
|
|
313
|
+
replaceRuns(restoredRuns);
|
|
314
|
+
},
|
|
315
|
+
async flush() {
|
|
316
|
+
while (draining || pendingReport) await drainPromise;
|
|
317
|
+
},
|
|
318
|
+
dispose() {
|
|
319
|
+
if (disposed) return;
|
|
320
|
+
clearAttention();
|
|
321
|
+
acknowledgedAttention.clear();
|
|
322
|
+
runs.clear();
|
|
323
|
+
syncBusy();
|
|
324
|
+
syncRefreshTimer();
|
|
325
|
+
publish();
|
|
326
|
+
for (const unsubscribe of subscriptions) unsubscribe();
|
|
327
|
+
disposed = true;
|
|
328
|
+
},
|
|
329
|
+
};
|
|
330
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import type { AgentConfig } from "../agents/agents.ts";
|
|
5
|
+
import type { ExtensionConfig, IntercomBridgeConfig, IntercomBridgeMode } from "../shared/types.ts";
|
|
6
|
+
import { getAgentDir } from "../shared/utils.ts";
|
|
7
|
+
|
|
8
|
+
export const NATIVE_INTERCOM_EXTENSION_DIR = "native:pi-subagents-supervisor-channel";
|
|
9
|
+
|
|
10
|
+
function defaultAgentDir(): string {
|
|
11
|
+
return getAgentDir();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function defaultSubagentConfigDir(agentDir = defaultAgentDir()): string {
|
|
15
|
+
return path.join(agentDir, "extensions", "subagent");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const DEFAULT_INTERCOM_TARGET_PREFIX = "subagent-chat";
|
|
19
|
+
export const PI_INTERCOM_SESSION_ID_ENV = "PI_INTERCOM_SESSION_ID";
|
|
20
|
+
export const INTERCOM_BRIDGE_MARKER = "Intercom orchestration channel:";
|
|
21
|
+
const DEFAULT_INTERCOM_BRIDGE_TEMPLATE = `The inherited thread is reference-only. Do not continue that conversation or send questions, status updates, or completion handoffs to the supervisor in normal assistant text.
|
|
22
|
+
|
|
23
|
+
Use contact_supervisor first. It resolves the supervisor session "{orchestratorTarget}" and run metadata automatically.
|
|
24
|
+
- Need a decision, blocked, approval, or product/API/scope ambiguity: contact_supervisor({ reason: "need_decision", message: "<question>" })
|
|
25
|
+
- Need structured supervisor input rather than a freeform reply: contact_supervisor({ reason: "interview_request", message: "<what input is needed>", interview: { title: "...", questions: [] } })
|
|
26
|
+
- After contact_supervisor with reason "need_decision" or "interview_request", stay alive and continue only after the reply arrives. Do not finish your final response with a choose-one question.
|
|
27
|
+
- Do not ask for clarification when the only conflict is review-only/no-edit versus progress-writing or artifact-writing instructions. If an output path is configured but no write-capable tool is available, return the complete artifact in your final response; the runtime will persist it. Do not contact the supervisor merely because you cannot write that output path directly.
|
|
28
|
+
- Meaningful progress or unexpected discoveries that change the plan: contact_supervisor({ reason: "progress_update", message: "UPDATE: <summary>" })
|
|
29
|
+
- Generic intercom is lower-level plumbing/fallback only: intercom({ action: "ask", to: "{orchestratorTarget}", message: "<question>" })
|
|
30
|
+
|
|
31
|
+
Do not use contact_supervisor or intercom for routine completion handoffs. If no coordination is needed, return a focused task result.`;
|
|
32
|
+
|
|
33
|
+
export interface IntercomBridgeState {
|
|
34
|
+
active: boolean;
|
|
35
|
+
mode: IntercomBridgeMode;
|
|
36
|
+
resultDelivery: boolean;
|
|
37
|
+
orchestratorTarget?: string;
|
|
38
|
+
extensionDir: string;
|
|
39
|
+
instruction: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface IntercomBridgeDiagnostic {
|
|
43
|
+
active: boolean;
|
|
44
|
+
mode: IntercomBridgeMode;
|
|
45
|
+
wantsIntercom: boolean;
|
|
46
|
+
supervisorChannelAvailable: boolean;
|
|
47
|
+
extensionDir: string;
|
|
48
|
+
orchestratorTarget?: string;
|
|
49
|
+
reason?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface ResolveIntercomBridgeInput {
|
|
53
|
+
config: ExtensionConfig["intercomBridge"];
|
|
54
|
+
context: "fresh" | "fork" | undefined;
|
|
55
|
+
orchestratorTarget?: string;
|
|
56
|
+
cwd?: string;
|
|
57
|
+
settingsDir?: string;
|
|
58
|
+
agentDir?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function resolveIntercomSessionTarget(sessionName: string | undefined, sessionId: string, intercomSessionId = process.env[PI_INTERCOM_SESSION_ID_ENV]): string {
|
|
62
|
+
const trimmedName = sessionName?.trim();
|
|
63
|
+
if (trimmedName) return trimmedName;
|
|
64
|
+
const fallbackSessionId = intercomSessionId?.trim() || sessionId;
|
|
65
|
+
const normalizedSessionId = fallbackSessionId.startsWith("session-") ? fallbackSessionId.slice("session-".length) : fallbackSessionId;
|
|
66
|
+
return `${DEFAULT_INTERCOM_TARGET_PREFIX}-${normalizedSessionId.slice(0, 8)}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function sanitizeIntercomTargetPart(value: string): string {
|
|
70
|
+
return value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "agent";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function resolveSubagentIntercomTarget(runId: string, agent: string, index?: number): string {
|
|
74
|
+
const stepSuffix = index !== undefined ? `-${index + 1}` : "";
|
|
75
|
+
return `subagent-${sanitizeIntercomTargetPart(agent)}-${sanitizeIntercomTargetPart(runId)}${stepSuffix}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function resolveIntercomBridgeMode(value: unknown): IntercomBridgeMode {
|
|
79
|
+
if (value === "off" || value === "always" || value === "fork-only") return value;
|
|
80
|
+
return "always";
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function resolveIntercomBridgeConfig(value: ExtensionConfig["intercomBridge"]): Required<IntercomBridgeConfig> {
|
|
84
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
85
|
+
return { mode: "always", instructionFile: "", resultDelivery: false };
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
mode: resolveIntercomBridgeMode(value.mode),
|
|
89
|
+
instructionFile: typeof value.instructionFile === "string" ? value.instructionFile : "",
|
|
90
|
+
resultDelivery: value.resultDelivery === true,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function expandTilde(filePath: string): string {
|
|
95
|
+
return filePath.startsWith("~/") ? path.join(os.homedir(), filePath.slice(2)) : filePath;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function resolveInstructionTemplate(instructionFile: string, settingsDir: string): string {
|
|
99
|
+
if (!instructionFile) return DEFAULT_INTERCOM_BRIDGE_TEMPLATE;
|
|
100
|
+
const expandedPath = expandTilde(instructionFile);
|
|
101
|
+
const resolvedPath = path.isAbsolute(expandedPath)
|
|
102
|
+
? expandedPath
|
|
103
|
+
: path.resolve(settingsDir, expandedPath);
|
|
104
|
+
try {
|
|
105
|
+
return fs.readFileSync(resolvedPath, "utf-8");
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.warn(`Failed to read intercom bridge instructionFile at '${resolvedPath}'. Using default instructions.`, error);
|
|
108
|
+
return DEFAULT_INTERCOM_BRIDGE_TEMPLATE;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function buildIntercomBridgeInstruction(orchestratorTarget: string, template: string): string {
|
|
113
|
+
const instruction = template.replaceAll("{orchestratorTarget}", orchestratorTarget).trim();
|
|
114
|
+
if (instruction.startsWith(INTERCOM_BRIDGE_MARKER)) return instruction;
|
|
115
|
+
return `${INTERCOM_BRIDGE_MARKER}\n${instruction}`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function inactiveReason(mode: IntercomBridgeMode, context: "fresh" | "fork" | undefined, orchestratorTarget: string | undefined): string | undefined {
|
|
119
|
+
if (mode === "off") return "bridge mode is off";
|
|
120
|
+
if (mode === "fork-only" && context !== "fork") return "bridge mode is fork-only and context is not fork";
|
|
121
|
+
if (!orchestratorTarget) return "orchestrator target is not available";
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function diagnoseIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeDiagnostic {
|
|
126
|
+
const config = resolveIntercomBridgeConfig(input.config);
|
|
127
|
+
const mode = config.mode;
|
|
128
|
+
const orchestratorTarget = input.orchestratorTarget?.trim();
|
|
129
|
+
const wantsIntercom = mode !== "off" && !(mode === "fork-only" && input.context !== "fork");
|
|
130
|
+
const reason = inactiveReason(mode, input.context, orchestratorTarget);
|
|
131
|
+
return {
|
|
132
|
+
active: reason === undefined,
|
|
133
|
+
mode,
|
|
134
|
+
wantsIntercom,
|
|
135
|
+
supervisorChannelAvailable: true,
|
|
136
|
+
extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
|
|
137
|
+
...(orchestratorTarget ? { orchestratorTarget } : {}),
|
|
138
|
+
...(reason ? { reason } : {}),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function resolveIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeState {
|
|
143
|
+
const config = resolveIntercomBridgeConfig(input.config);
|
|
144
|
+
const mode = config.mode;
|
|
145
|
+
const orchestratorTarget = input.orchestratorTarget?.trim();
|
|
146
|
+
const agentDir = path.resolve(input.agentDir ?? defaultAgentDir());
|
|
147
|
+
const settingsDir = path.resolve(input.settingsDir ?? defaultSubagentConfigDir(agentDir));
|
|
148
|
+
const defaultInstruction = buildIntercomBridgeInstruction(
|
|
149
|
+
orchestratorTarget || "{orchestratorTarget}",
|
|
150
|
+
DEFAULT_INTERCOM_BRIDGE_TEMPLATE,
|
|
151
|
+
);
|
|
152
|
+
const reason = inactiveReason(mode, input.context, orchestratorTarget);
|
|
153
|
+
if (reason || !orchestratorTarget) {
|
|
154
|
+
return { active: false, mode, resultDelivery: config.resultDelivery, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
active: true,
|
|
158
|
+
mode,
|
|
159
|
+
resultDelivery: config.resultDelivery,
|
|
160
|
+
orchestratorTarget,
|
|
161
|
+
extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
|
|
162
|
+
instruction: buildIntercomBridgeInstruction(orchestratorTarget, resolveInstructionTemplate(config.instructionFile, settingsDir)),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function applyIntercomBridgeToAgent(agent: AgentConfig, bridge: IntercomBridgeState): AgentConfig {
|
|
167
|
+
if (!bridge.active || !bridge.orchestratorTarget) return agent;
|
|
168
|
+
|
|
169
|
+
const bridgeTools = ["intercom", "contact_supervisor"];
|
|
170
|
+
const tools = agent.tools && agent.tools.length > 0
|
|
171
|
+
? [...agent.tools, ...bridgeTools.filter((tool) => !agent.tools?.includes(tool))]
|
|
172
|
+
: agent.tools;
|
|
173
|
+
const instruction = bridge.instruction;
|
|
174
|
+
const trimmedPrompt = agent.systemPrompt?.trim() || "";
|
|
175
|
+
const systemPrompt = trimmedPrompt.includes(INTERCOM_BRIDGE_MARKER)
|
|
176
|
+
? trimmedPrompt
|
|
177
|
+
: trimmedPrompt
|
|
178
|
+
? `${trimmedPrompt}\n\n${instruction}`
|
|
179
|
+
: instruction;
|
|
180
|
+
|
|
181
|
+
if (tools === agent.tools && systemPrompt === agent.systemPrompt) return agent;
|
|
182
|
+
return {
|
|
183
|
+
...agent,
|
|
184
|
+
tools,
|
|
185
|
+
systemPrompt,
|
|
186
|
+
};
|
|
187
|
+
}
|