ceulen 0.26.2 → 0.28.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 +112 -0
- package/extensions/lib/registry.ts +1 -1
- package/extensions/modules/subagent/index.ts +528 -75
- package/extensions/modules/subagent/lib/herdr-app.ts +917 -0
- package/extensions/modules/subagent/lib/herdr.ts +50 -29
- package/extensions/modules/subagent/lib/render.ts +33 -2
- package/extensions/modules/subagent/lib/rex.ts +902 -0
- package/extensions/modules/subagent/lib/runner.ts +5 -0
- package/extensions/modules/subagent/lib/widget.ts +8 -6
- package/extensions/modules/subagent/test/herdr-app.test.ts +572 -0
- package/extensions/modules/subagent/test/render-hint.test.ts +31 -0
- package/extensions/modules/subagent/test/rex.test.ts +724 -0
- package/extensions/modules/web/test/configPanel.test.ts +20 -3
- package/extensions/modules/web/test/settings.test.ts +6 -1
- package/package.json +1 -1
|
@@ -88,10 +88,56 @@ import { startBackgroundTask,
|
|
|
88
88
|
clearBackgroundTasks,
|
|
89
89
|
} from "./lib/background.ts";
|
|
90
90
|
import { parseStructuredResult } from "./lib/result.ts";
|
|
91
|
+
import { formatChainReport } from "./lib/render.ts";
|
|
91
92
|
import { skillsRoot } from "../../lib/skill-path.js";
|
|
92
93
|
import { isChildSession } from "../../lib/child-session.js";
|
|
93
94
|
import { appendHistory, readHistory, markInterruptedOnRestart, trimHistory, getHistoryPath } from "./lib/history.ts";
|
|
94
95
|
import { herdrCli } from './lib/herdr.ts';
|
|
96
|
+
import {
|
|
97
|
+
appTabCloseBlockers,
|
|
98
|
+
cancelAppAgent,
|
|
99
|
+
closeAppTab,
|
|
100
|
+
collectAppResult,
|
|
101
|
+
executeHerdrAppTask,
|
|
102
|
+
findHerdrAppAgent,
|
|
103
|
+
focusAppTab,
|
|
104
|
+
getHerdrAppRegistry,
|
|
105
|
+
getTerminal as getAppTerminal,
|
|
106
|
+
herdrAppCli,
|
|
107
|
+
herdrAppDisabled,
|
|
108
|
+
herdrAppEnvDetected,
|
|
109
|
+
prepareHerdrAppTask,
|
|
110
|
+
probeHerdrAppBinary,
|
|
111
|
+
promptAppAndWait,
|
|
112
|
+
readAppTerminal,
|
|
113
|
+
sendAppPrompt,
|
|
114
|
+
wrapAppTaskPrompt,
|
|
115
|
+
forgetHerdrAppTab,
|
|
116
|
+
type HerdrAppHandle,
|
|
117
|
+
} from "./lib/herdr-app.ts";
|
|
118
|
+
import {
|
|
119
|
+
cancelRexAgent,
|
|
120
|
+
closeRexWindow,
|
|
121
|
+
collectRexResult,
|
|
122
|
+
executeRexTask,
|
|
123
|
+
findRexAgent,
|
|
124
|
+
focusRexWindow,
|
|
125
|
+
forgetRexAgent,
|
|
126
|
+
forgetRexWindow,
|
|
127
|
+
getRexRegistry,
|
|
128
|
+
getRexTerminal as getRexTerminalState,
|
|
129
|
+
prepareRexTask,
|
|
130
|
+
probeRexBinary,
|
|
131
|
+
promptRexAndWait,
|
|
132
|
+
readRexBlock,
|
|
133
|
+
rexCli,
|
|
134
|
+
rexDisabled,
|
|
135
|
+
rexEnvDetected,
|
|
136
|
+
rexWindowCloseBlockers,
|
|
137
|
+
sendRexPrompt,
|
|
138
|
+
wrapRexTaskPrompt,
|
|
139
|
+
type RexHandle,
|
|
140
|
+
} from "./lib/rex.ts";
|
|
95
141
|
/** Keep-alive cadence for herdr delegations (test seam: shorten to assert). */
|
|
96
142
|
export const herdrHeartbeat = { intervalMs: 30_000 };
|
|
97
143
|
import {
|
|
@@ -104,7 +150,7 @@ import {
|
|
|
104
150
|
getAgentInfo,
|
|
105
151
|
herdrDisabled,
|
|
106
152
|
getHerdrRegistry,
|
|
107
|
-
|
|
153
|
+
herdrTuiEnvDetected,
|
|
108
154
|
herdrTabCloseBlockers,
|
|
109
155
|
isDelegatedHerdrAgent,
|
|
110
156
|
listHerdrAgents,
|
|
@@ -126,6 +172,9 @@ import {
|
|
|
126
172
|
// Constants
|
|
127
173
|
// ---------------------------------------------------------------------------
|
|
128
174
|
|
|
175
|
+
/** Visible-pane delegation backend for one dispatch. */
|
|
176
|
+
type RunnerKind = "sdk" | "herdr" | "herdr-app" | "rex";
|
|
177
|
+
|
|
129
178
|
// ---------------------------------------------------------------------------
|
|
130
179
|
// Helpers
|
|
131
180
|
// ---------------------------------------------------------------------------
|
|
@@ -214,7 +263,7 @@ const SubagentParams = Type.Object({
|
|
|
214
263
|
instructions: Type.Optional(Type.String({ description: "Bounded repository/task instructions passed to each child (max 16 KB)" })),
|
|
215
264
|
solutionSpace: Type.Optional(Type.String({ description: "Single/parallel mode: how open-ended the child's problem is (design given vs choices open). Feeds model-tier/thinking routing; never mention siblings. e.g. 'one fix: rename, names given' vs 'several retry API shapes; error classes to choose'." })),
|
|
216
265
|
runner: Type.Optional(StringEnum(["sdk", "herdr"] as const, {
|
|
217
|
-
description: 'Execution backend: "sdk" (in-process, lean) or "herdr" (visible interactive pi panes
|
|
266
|
+
description: 'Execution backend: "sdk" (in-process, lean) or "herdr" (visible interactive pi panes; one tab per agent type, one pane per instance). Default: automatic — herdr TUI inside a herdr pane (HERDR_ENV), rex inside a Rex terminal (REX_SESSION), herdr-app inside a Herdr app/core terminal (HC_TERMINAL_ID), otherwise sdk.',
|
|
218
267
|
})),
|
|
219
268
|
abortOnFailure: Type.Optional(Type.Boolean({ description: "In parallel mode, cancel remaining tasks when one fails. Default: false.", default: false })),
|
|
220
269
|
});
|
|
@@ -230,8 +279,8 @@ interface SubagentDetails {
|
|
|
230
279
|
results: SubAgentResult[];
|
|
231
280
|
/** Set when a background task was started (single mode + background:true). */
|
|
232
281
|
backgroundTaskId?: string;
|
|
233
|
-
/** Set when the run was delegated to
|
|
234
|
-
runner?: "herdr";
|
|
282
|
+
/** Set when the run was delegated to a visible-pane backend. */
|
|
283
|
+
runner?: "herdr" | "herdr-app" | "rex";
|
|
235
284
|
}
|
|
236
285
|
|
|
237
286
|
// ---------------------------------------------------------------------------
|
|
@@ -645,6 +694,33 @@ ${lines.join("\n")}`;
|
|
|
645
694
|
return found?.color ? AGENT_TO_THEME_COLOR[found.color] : "accent";
|
|
646
695
|
};
|
|
647
696
|
|
|
697
|
+
/**
|
|
698
|
+
* Effective runner across ALL THREE visible-pane backends.
|
|
699
|
+
*
|
|
700
|
+
* herdr TUI (`HERDR_ENV=1`, `herdr` CLI) keeps its exact existing semantics
|
|
701
|
+
* (lib/herdr.ts resolveEffectiveRunner: explicit params, errors, probe).
|
|
702
|
+
* rex (`REX_SESSION`, `rex` CLI) and herdr-app (`HC_TERMINAL_ID`,
|
|
703
|
+
* `herdr-app` + `hc`) are AUTO fallbacks: when no explicit runner was named
|
|
704
|
+
* and the TUI path did not claim the call, delegate to that backend's panes.
|
|
705
|
+
* Both markers are independent (Rex sets REX_SESSION, herdr-core sets
|
|
706
|
+
* HC_TERMINAL_ID) and either can be present alone, so each probe stands on
|
|
707
|
+
* its own. An explicit `runner:"herdr"` never silently re-routes — its
|
|
708
|
+
* "not running inside herdr" error stays.
|
|
709
|
+
*/
|
|
710
|
+
async function resolveRunner(
|
|
711
|
+
requested: "sdk" | "herdr" | undefined,
|
|
712
|
+
subagentSettings: { herdr?: unknown } | undefined,
|
|
713
|
+
): Promise<{ runner: RunnerKind; error?: string }> {
|
|
714
|
+
const tui = await resolveEffectiveRunner(requested, subagentSettings, herdrCli.exec);
|
|
715
|
+
if (tui.runner === "herdr" || tui.error || requested !== undefined) return tui;
|
|
716
|
+
if (rexEnvDetected() && !rexDisabled(subagentSettings) && await probeRexBinary(rexCli.exec)) {
|
|
717
|
+
return { runner: "rex" };
|
|
718
|
+
}
|
|
719
|
+
if (!herdrAppEnvDetected() || herdrAppDisabled(subagentSettings)) return tui;
|
|
720
|
+
if (!await probeHerdrAppBinary(herdrAppCli.exec)) return tui;
|
|
721
|
+
return { runner: "herdr-app" };
|
|
722
|
+
}
|
|
723
|
+
|
|
648
724
|
pi.registerTool({
|
|
649
725
|
name: "subagent",
|
|
650
726
|
label: "Subagent",
|
|
@@ -665,9 +741,9 @@ ${lines.join("\n")}`;
|
|
|
665
741
|
"For background single tasks use background:true — you will be notified on completion; DO NOT poll or sleep.",
|
|
666
742
|
'Task control by taskId: operation "status" (snapshot + liveness age), "wait" (block until settled or waitTimeoutMs, then snapshot), "cancel" (abort). A task producing output is NEVER hard-killed; only total silence (idle timeout) aborts it. "STALLED" in a snapshot means no child activity — cancel it or keep waiting.',
|
|
667
743
|
"Set solutionSpace when a task's openness isn't obvious from its text — it feeds tier/thinking routing.",
|
|
668
|
-
"Inside herdr, a single dispatch that names neither runner nor background may be sent to background by the task classifier (long/self-contained work) — pass runner or background explicitly to force one.",
|
|
744
|
+
"Inside herdr (TUI or app) or Rex, a single dispatch that names neither runner nor background may be sent to background by the task classifier (long/self-contained work) — pass runner or background explicitly to force one.",
|
|
669
745
|
"Worktree-sandboxed agents return their diff as a patch block in the result; pass merge: \"3way\" to auto-apply it to the parent checkout (git apply --3way; conflicts reported, never silently resolved).",
|
|
670
|
-
`Runner: "sdk" runs agents in-process (lean, default outside
|
|
746
|
+
`Runner: "sdk" runs agents in-process (lean, default outside a multiplexer); "herdr" delegates to visible interactive pi panes (one tab per agent type, one pane per instance) — the default inside the herdr TUI (HERDR_ENV), inside a Herdr app/core terminal (HC_TERMINAL_ID, via herdr-app + hc), and inside a Rex terminal (REX_SESSION, via the rex CLI). Pane children share the working tree and skip worktree isolation; background:true always uses the sdk runner.`,
|
|
671
747
|
"Use /subagent list to list all available agents, /subagent <name> for agent details, /subagent @role for role detail.",
|
|
672
748
|
],
|
|
673
749
|
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
@@ -702,11 +778,7 @@ ${lines.join("\n")}`;
|
|
|
702
778
|
(params.operation !== undefined || params.background === true);
|
|
703
779
|
const runnerResolved = skipRunnerResolution
|
|
704
780
|
? { runner: "sdk" as const }
|
|
705
|
-
: await
|
|
706
|
-
params.runner,
|
|
707
|
-
(ctx as any).settings?.subagent ?? {},
|
|
708
|
-
herdrCli.exec,
|
|
709
|
-
);
|
|
781
|
+
: await resolveRunner(params.runner, (ctx as any).settings?.subagent ?? {});
|
|
710
782
|
if (runnerResolved.error) {
|
|
711
783
|
return {
|
|
712
784
|
content: [{ type: "text", text: runnerResolved.error }],
|
|
@@ -716,7 +788,8 @@ ${lines.join("\n")}`;
|
|
|
716
788
|
}
|
|
717
789
|
// background:true always runs the in-process SDK runner (herdr tasks are
|
|
718
790
|
// foreground) — keep the details stamp honest.
|
|
719
|
-
const
|
|
791
|
+
const runnerKind: RunnerKind = params.background ? "sdk" : runnerResolved.runner;
|
|
792
|
+
const herdrActive = runnerKind !== "sdk";
|
|
720
793
|
|
|
721
794
|
// Worktree isolation / merge:"3way" is an SDK-runner feature — herdr
|
|
722
795
|
// children share the parent's working tree, so a silent drop would turn
|
|
@@ -727,7 +800,7 @@ ${lines.join("\n")}`;
|
|
|
727
800
|
.some((n) => agents.find((a) => a.name === n)?.sandbox === "worktree");
|
|
728
801
|
if (herdrActive && (requestedMerge || worktreeAgentRequested)) {
|
|
729
802
|
return {
|
|
730
|
-
content: [{ type: "text", text: `Worktree isolation${requestedMerge ? " / merge:\"3way\"" : ""} requires runner:"sdk" — herdr children share the parent's working tree. Re-run with runner:"sdk"${requestedMerge ? " or drop merge" : ""}.` }],
|
|
803
|
+
content: [{ type: "text", text: `Worktree isolation${requestedMerge ? " / merge:\"3way\"" : ""} requires runner:"sdk" — herdr/herdr-app/rex children share the parent's working tree. Re-run with runner:"sdk"${requestedMerge ? " or drop merge" : ""}.` }],
|
|
731
804
|
details: { mode: "single" as const, agentScope, projectAgentsDir: discovery.projectAgentsDir, results: [] },
|
|
732
805
|
isError: true,
|
|
733
806
|
};
|
|
@@ -740,7 +813,7 @@ ${lines.join("\n")}`;
|
|
|
740
813
|
agentScope,
|
|
741
814
|
projectAgentsDir: discovery.projectAgentsDir,
|
|
742
815
|
results,
|
|
743
|
-
runner: herdrActive ?
|
|
816
|
+
runner: herdrActive ? runnerKind : undefined,
|
|
744
817
|
});
|
|
745
818
|
|
|
746
819
|
// Task-control results (operation status/cancel) describe an existing
|
|
@@ -1029,11 +1102,11 @@ ${lines.join("\n")}`;
|
|
|
1029
1102
|
};
|
|
1030
1103
|
}
|
|
1031
1104
|
|
|
1032
|
-
// Helper: widget progress snapshot from a
|
|
1033
|
-
function herdrProgress(agentName: string, task: string, state: string, startedAt: number, timeoutMs: number): SubAgentProgress {
|
|
1105
|
+
// Helper: widget progress snapshot from a pane lifecycle state.
|
|
1106
|
+
function herdrProgress(agentName: string, task: string, state: string, startedAt: number, timeoutMs: number, kind: "herdr" | "herdr-app" | "rex" = "herdr"): SubAgentProgress {
|
|
1034
1107
|
const now = Date.now();
|
|
1035
1108
|
return {
|
|
1036
|
-
label:
|
|
1109
|
+
label: `${kind}: ${state}`,
|
|
1037
1110
|
at: now,
|
|
1038
1111
|
elapsedMs: now - startedAt,
|
|
1039
1112
|
inactivityDeadline: now + timeoutMs,
|
|
@@ -1087,17 +1160,26 @@ ${lines.join("\n")}`;
|
|
|
1087
1160
|
};
|
|
1088
1161
|
}
|
|
1089
1162
|
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
async function
|
|
1163
|
+
/** Shared prelude for BOTH visible-pane backends: validate the agent,
|
|
1164
|
+
* route model+thinking, resolve the lifetime cap and the safe cwd.
|
|
1165
|
+
* Keeps the TUI and herdr-app prepares from drifting apart. */
|
|
1166
|
+
async function resolvePaneDispatch(
|
|
1094
1167
|
agentName: string,
|
|
1095
1168
|
task: string,
|
|
1096
1169
|
cwd: string | undefined,
|
|
1097
1170
|
timeoutMs: number | undefined,
|
|
1098
1171
|
solutionSpace?: string,
|
|
1099
1172
|
verdict?: RoutingVerdict,
|
|
1100
|
-
): Promise<{
|
|
1173
|
+
): Promise<{
|
|
1174
|
+
agentType: string;
|
|
1175
|
+
systemPrompt: string;
|
|
1176
|
+
model: string;
|
|
1177
|
+
thinking?: string;
|
|
1178
|
+
tools?: string[];
|
|
1179
|
+
readOnly: boolean;
|
|
1180
|
+
cwd: string;
|
|
1181
|
+
timeoutMs: number;
|
|
1182
|
+
} | { error: string }> {
|
|
1101
1183
|
const agent = agents.find((a) => a.name === agentName);
|
|
1102
1184
|
if (!agent) return { error: `Unknown agent: "${agentName}".` };
|
|
1103
1185
|
const { chain: agentChain, defaultThinking, error: chainError } = await routedChain(agent, task, solutionSpace, verdict);
|
|
@@ -1106,7 +1188,7 @@ ${lines.join("\n")}`;
|
|
|
1106
1188
|
if (!resolved.model) {
|
|
1107
1189
|
return { error: `No model resolved for agent "${agentName}" (tried: ${resolved.attempted.join(", ") || "none"}).` };
|
|
1108
1190
|
}
|
|
1109
|
-
//
|
|
1191
|
+
// Pane children run full pi — they need SOME lifetime cap so an
|
|
1110
1192
|
// unattended pane can't run forever. The IDLE window is NOT a lifetime
|
|
1111
1193
|
// cap (live incident 2026-10-06: a healthy 13-min chapter write was
|
|
1112
1194
|
// abandoned at the default 3-min idle window — the pane kept working,
|
|
@@ -1116,33 +1198,121 @@ ${lines.join("\n")}`;
|
|
|
1116
1198
|
const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, idleTimeoutMins: subSettings.idleTimeoutMins, hardTimeoutMins: subSettings.hardTimeoutMins });
|
|
1117
1199
|
if (timeouts.error) return { error: timeouts.error };
|
|
1118
1200
|
const hardTimeoutMs = timeouts.hardTimeoutMs ?? MAX_TIMEOUT_MS;
|
|
1119
|
-
if (!hardTimeoutMs) return { error: "Invalid
|
|
1201
|
+
if (!hardTimeoutMs) return { error: "Invalid pane timeout configuration." };
|
|
1120
1202
|
const safe = resolveSafeCwd({ workspaceRoot, childCwd: cwd, allowExternalCwd });
|
|
1121
1203
|
if (safe.error) return { error: safe.error };
|
|
1122
|
-
const startedAt = Date.now();
|
|
1123
1204
|
const systemPrompt = params.instructions
|
|
1124
1205
|
? `${agent.systemPrompt}\n\n## Task Contract\n${params.instructions.slice(0, MAX_INSTRUCTIONS_LENGTH)}`
|
|
1125
1206
|
: agent.systemPrompt;
|
|
1207
|
+
return {
|
|
1208
|
+
agentType: agent.name,
|
|
1209
|
+
systemPrompt,
|
|
1210
|
+
model: `${resolved.model.provider}/${resolved.model.id}`,
|
|
1211
|
+
thinking: agentChain.thinkingByCandidate.get(resolved.matchedCandidate ?? "") ?? defaultThinking,
|
|
1212
|
+
tools: agent.tools,
|
|
1213
|
+
readOnly: agent.sandbox === "read-only",
|
|
1214
|
+
cwd: safe.path,
|
|
1215
|
+
timeoutMs: hardTimeoutMs,
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
// Helper (herdr runner): validate + create topology + start the child pi,
|
|
1220
|
+
// without prompting — so parallel dispatch can materialise every pane
|
|
1221
|
+
// up front before any work starts.
|
|
1222
|
+
async function prepareHerdrOne(
|
|
1223
|
+
agentName: string,
|
|
1224
|
+
task: string,
|
|
1225
|
+
cwd: string | undefined,
|
|
1226
|
+
timeoutMs: number | undefined,
|
|
1227
|
+
solutionSpace?: string,
|
|
1228
|
+
verdict?: RoutingVerdict,
|
|
1229
|
+
): Promise<{ handle: HerdrHandle; timeoutMs: number; startedAt: number } | { error: string }> {
|
|
1230
|
+
const plan = await resolvePaneDispatch(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
|
|
1231
|
+
if ("error" in plan) return { error: plan.error };
|
|
1232
|
+
const startedAt = Date.now();
|
|
1126
1233
|
try {
|
|
1127
1234
|
const handle = await prepareHerdrTask({
|
|
1128
|
-
agentType:
|
|
1129
|
-
systemPrompt,
|
|
1235
|
+
agentType: plan.agentType,
|
|
1236
|
+
systemPrompt: plan.systemPrompt,
|
|
1130
1237
|
task,
|
|
1131
|
-
cwd:
|
|
1132
|
-
model:
|
|
1133
|
-
thinking:
|
|
1134
|
-
tools:
|
|
1135
|
-
readOnly:
|
|
1136
|
-
timeoutMs:
|
|
1238
|
+
cwd: plan.cwd,
|
|
1239
|
+
model: plan.model,
|
|
1240
|
+
thinking: plan.thinking,
|
|
1241
|
+
tools: plan.tools,
|
|
1242
|
+
readOnly: plan.readOnly,
|
|
1243
|
+
timeoutMs: plan.timeoutMs,
|
|
1137
1244
|
});
|
|
1138
|
-
return { handle, timeoutMs:
|
|
1245
|
+
return { handle, timeoutMs: plan.timeoutMs, startedAt };
|
|
1139
1246
|
} catch (err) {
|
|
1140
1247
|
return { error: err instanceof Error ? err.message : String(err) };
|
|
1141
1248
|
}
|
|
1142
1249
|
}
|
|
1143
1250
|
|
|
1144
|
-
// Helper (herdr runner):
|
|
1145
|
-
async function
|
|
1251
|
+
// Helper (herdr-app runner): the same prelude, delegated to app panes.
|
|
1252
|
+
async function prepareHerdrAppOne(
|
|
1253
|
+
agentName: string,
|
|
1254
|
+
task: string,
|
|
1255
|
+
cwd: string | undefined,
|
|
1256
|
+
timeoutMs: number | undefined,
|
|
1257
|
+
solutionSpace?: string,
|
|
1258
|
+
verdict?: RoutingVerdict,
|
|
1259
|
+
): Promise<{ handle: HerdrAppHandle; timeoutMs: number; startedAt: number } | { error: string }> {
|
|
1260
|
+
const plan = await resolvePaneDispatch(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
|
|
1261
|
+
if ("error" in plan) return { error: plan.error };
|
|
1262
|
+
const startedAt = Date.now();
|
|
1263
|
+
try {
|
|
1264
|
+
const handle = await prepareHerdrAppTask({
|
|
1265
|
+
agentType: plan.agentType,
|
|
1266
|
+
systemPrompt: plan.systemPrompt,
|
|
1267
|
+
task,
|
|
1268
|
+
cwd: plan.cwd,
|
|
1269
|
+
model: plan.model,
|
|
1270
|
+
thinking: plan.thinking,
|
|
1271
|
+
tools: plan.tools,
|
|
1272
|
+
readOnly: plan.readOnly,
|
|
1273
|
+
timeoutMs: plan.timeoutMs,
|
|
1274
|
+
});
|
|
1275
|
+
return { handle, timeoutMs: plan.timeoutMs, startedAt };
|
|
1276
|
+
} catch (err) {
|
|
1277
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
// Helper (rex runner): the same prelude, delegated to rex panes.
|
|
1282
|
+
async function prepareRexOne(
|
|
1283
|
+
agentName: string,
|
|
1284
|
+
task: string,
|
|
1285
|
+
cwd: string | undefined,
|
|
1286
|
+
timeoutMs: number | undefined,
|
|
1287
|
+
solutionSpace?: string,
|
|
1288
|
+
verdict?: RoutingVerdict,
|
|
1289
|
+
): Promise<{ handle: RexHandle; timeoutMs: number; startedAt: number } | { error: string }> {
|
|
1290
|
+
const plan = await resolvePaneDispatch(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
|
|
1291
|
+
if ("error" in plan) return { error: plan.error };
|
|
1292
|
+
const startedAt = Date.now();
|
|
1293
|
+
try {
|
|
1294
|
+
const handle = await prepareRexTask({
|
|
1295
|
+
agentType: plan.agentType,
|
|
1296
|
+
systemPrompt: plan.systemPrompt,
|
|
1297
|
+
task,
|
|
1298
|
+
cwd: plan.cwd,
|
|
1299
|
+
model: plan.model,
|
|
1300
|
+
thinking: plan.thinking,
|
|
1301
|
+
tools: plan.tools,
|
|
1302
|
+
readOnly: plan.readOnly,
|
|
1303
|
+
timeoutMs: plan.timeoutMs,
|
|
1304
|
+
});
|
|
1305
|
+
return { handle, timeoutMs: plan.timeoutMs, startedAt };
|
|
1306
|
+
} catch (err) {
|
|
1307
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// Helper (herdr + herdr-app + rex runners): full delegation (prepare +
|
|
1312
|
+
// prompt + collect). The backends differ only in prepare/execute/cancel,
|
|
1313
|
+
// so one flow keeps their abort + keep-alive semantics identical.
|
|
1314
|
+
async function startPaneOne(
|
|
1315
|
+
kind: "herdr" | "herdr-app" | "rex",
|
|
1146
1316
|
agentName: string,
|
|
1147
1317
|
task: string,
|
|
1148
1318
|
cwd: string | undefined,
|
|
@@ -1155,9 +1325,17 @@ ${lines.join("\n")}`;
|
|
|
1155
1325
|
solutionSpace?: string,
|
|
1156
1326
|
verdict?: RoutingVerdict,
|
|
1157
1327
|
): Promise<SubAgentResult> {
|
|
1158
|
-
const
|
|
1328
|
+
const app = kind === "herdr-app";
|
|
1329
|
+
const rex = kind === "rex";
|
|
1330
|
+
const prepared = rex
|
|
1331
|
+
? await prepareRexOne(agentName, task, cwd, timeoutMs, solutionSpace, verdict)
|
|
1332
|
+
: app
|
|
1333
|
+
? await prepareHerdrAppOne(agentName, task, cwd, timeoutMs, solutionSpace, verdict)
|
|
1334
|
+
: await prepareHerdrOne(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
|
|
1159
1335
|
if ("error" in prepared) return makeErrorResult(agentName, task, prepared.error);
|
|
1160
|
-
const {
|
|
1336
|
+
const { startedAt } = prepared;
|
|
1337
|
+
// Narrowing the union by `app` keeps every later access type-safe.
|
|
1338
|
+
const handle = prepared.handle as HerdrAppHandle & HerdrHandle & RexHandle;
|
|
1161
1339
|
// Keep-alive parity with the SDK path: a long pane run must emit
|
|
1162
1340
|
// onUpdate traffic or the host may idle-abort the tool call.
|
|
1163
1341
|
const stopHeartbeat = onUpdate ? startHeartbeat(() => {
|
|
@@ -1165,29 +1343,51 @@ ${lines.join("\n")}`;
|
|
|
1165
1343
|
onUpdate({ content: [{ type: "text", text: "" }], details: heartbeatDetails?.() ?? makeDetails("single")([]) });
|
|
1166
1344
|
widget.requestRender();
|
|
1167
1345
|
}, herdrHeartbeat.intervalMs) : undefined;
|
|
1346
|
+
const paneRef = kind === "herdr-app" || rex ? handle.address : handle.name;
|
|
1347
|
+
const progress = (state: string) => onActivity?.(
|
|
1348
|
+
herdrProgress(handle.agentType, task, state, startedAt, prepared.timeoutMs, kind),
|
|
1349
|
+
);
|
|
1168
1350
|
let onCancel: (() => void) | undefined;
|
|
1169
1351
|
if (parentSignal) {
|
|
1170
|
-
onCancel = () => {
|
|
1352
|
+
onCancel = () => {
|
|
1353
|
+
void (rex
|
|
1354
|
+
? cancelRexAgent(paneRef, rexCli.exec)
|
|
1355
|
+
: kind === "herdr-app"
|
|
1356
|
+
? cancelAppAgent(paneRef, herdrAppCli.exec)
|
|
1357
|
+
: cancelAgent(paneRef, herdrCli.exec));
|
|
1358
|
+
};
|
|
1171
1359
|
// An already-aborted signal never fires its listeners — cancel now.
|
|
1172
1360
|
if (parentSignal.aborted) onCancel();
|
|
1173
1361
|
else parentSignal.addEventListener("abort", onCancel, { once: true });
|
|
1174
1362
|
}
|
|
1175
1363
|
try {
|
|
1364
|
+
if (rex) {
|
|
1365
|
+
return await executeRexTask(handle as RexHandle, {
|
|
1366
|
+
onState: onActivity ? progress : undefined,
|
|
1367
|
+
advisorWaitMs: subSettings.advisorWaitSecs * 1000,
|
|
1368
|
+
onAdvisorPhase: onActivity ? progress : undefined,
|
|
1369
|
+
signal: parentSignal,
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
if (app) {
|
|
1373
|
+
return await executeHerdrAppTask(handle, {
|
|
1374
|
+
onState: onActivity ? progress : undefined,
|
|
1375
|
+
advisorWaitMs: subSettings.advisorWaitSecs * 1000,
|
|
1376
|
+
onAdvisorPhase: onActivity ? progress : undefined,
|
|
1377
|
+
signal: parentSignal,
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1176
1380
|
return await executeHerdrTask(handle, {
|
|
1177
|
-
onState: onActivity
|
|
1178
|
-
? (state) => onActivity(herdrProgress(handle.agentType, task, state, startedAt, prepared.timeoutMs))
|
|
1179
|
-
: undefined,
|
|
1381
|
+
onState: onActivity ? progress : undefined,
|
|
1180
1382
|
// The child's own advisor reviews the settled turn and may steer a
|
|
1181
1383
|
// correction into it — wait for that verdict before collecting, so
|
|
1182
1384
|
// the parent never consumes a draft the child is about to fix.
|
|
1183
1385
|
advisorWaitMs: subSettings.advisorWaitSecs * 1000,
|
|
1184
|
-
onAdvisorPhase: onActivity
|
|
1185
|
-
? (phase) => onActivity(herdrProgress(handle.agentType, task, phase, startedAt, prepared.timeoutMs))
|
|
1186
|
-
: undefined,
|
|
1386
|
+
onAdvisorPhase: onActivity ? progress : undefined,
|
|
1187
1387
|
signal: parentSignal,
|
|
1188
1388
|
});
|
|
1189
1389
|
} catch (err) {
|
|
1190
|
-
return makeErrorResult(agentName, task,
|
|
1390
|
+
return makeErrorResult(agentName, task, `${kind} delegation failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1191
1391
|
} finally {
|
|
1192
1392
|
// Settled: stop the keep-alive and detach the abort listener so a
|
|
1193
1393
|
// later abort never keystrokes a completed step's pane.
|
|
@@ -1344,7 +1544,8 @@ ${lines.join("\n")}`;
|
|
|
1344
1544
|
const historyId = makeForegroundHistoryId(thread.createdAt);
|
|
1345
1545
|
recordForegroundStart(historyId, step.agent, dispatchTask, thread.createdAt);
|
|
1346
1546
|
const result = herdrActive
|
|
1347
|
-
? await
|
|
1547
|
+
? await startPaneOne(
|
|
1548
|
+
runnerKind as "herdr" | "herdr-app" | "rex",
|
|
1348
1549
|
step.agent, dispatchTask, step.cwd,
|
|
1349
1550
|
signal, step.timeout ?? params.timeout,
|
|
1350
1551
|
(progress) => threadStore.updateProgress(thread.id, progress),
|
|
@@ -1425,16 +1626,14 @@ ${lines.join("\n")}`;
|
|
|
1425
1626
|
}
|
|
1426
1627
|
|
|
1427
1628
|
const last = results[results.length - 1];
|
|
1428
|
-
// Chain deliverable:
|
|
1429
|
-
//
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1629
|
+
// Chain deliverable: the FINAL step's output first (what callers act
|
|
1630
|
+
// on), then every step's report so intermediate work is not lost —
|
|
1631
|
+
// `{previous}` only ever carries one step forward, so without this the
|
|
1632
|
+
// earlier findings vanish from the result. Patches stay labeled per
|
|
1633
|
+
// step so the parent can merge them in order.
|
|
1634
|
+
const finalText = getFinalOutput(last.messages) || "(no output)";
|
|
1434
1635
|
return {
|
|
1435
|
-
content: [
|
|
1436
|
-
{ type: "text", text: [getFinalOutput(last.messages) || "(no output)", chainPatches].filter(Boolean).join("\n\n") },
|
|
1437
|
-
],
|
|
1636
|
+
content: [{ type: "text", text: formatChainReport(finalText, results) }],
|
|
1438
1637
|
details: makeDetails("chain")(results),
|
|
1439
1638
|
};
|
|
1440
1639
|
}
|
|
@@ -1492,17 +1691,31 @@ ${lines.join("\n")}`;
|
|
|
1492
1691
|
// Herdr: materialise every pane up front so all delegated agents are
|
|
1493
1692
|
// visible in herdr before any work starts, then submit prompts under
|
|
1494
1693
|
// the concurrency limit below.
|
|
1694
|
+
const appPanes = runnerKind === "herdr-app";
|
|
1695
|
+
const rexPanes = runnerKind === "rex";
|
|
1696
|
+
// Every backend: a handle identifies its pane by `address` (app/rex)
|
|
1697
|
+
// or `name` (TUI) — one resolver keeps the cancel wiring honest.
|
|
1698
|
+
const paneRef = (h: HerdrHandle | HerdrAppHandle | RexHandle) => ("address" in h ? h.address : h.name);
|
|
1699
|
+
const cancelPane = (h: HerdrHandle | HerdrAppHandle | RexHandle) => {
|
|
1700
|
+
if (rexPanes) void cancelRexAgent(paneRef(h), rexCli.exec);
|
|
1701
|
+
else if (appPanes) void cancelAppAgent(paneRef(h), herdrAppCli.exec);
|
|
1702
|
+
else void cancelAgent(paneRef(h), herdrCli.exec);
|
|
1703
|
+
};
|
|
1495
1704
|
const herdrPrepared = herdrActive
|
|
1496
1705
|
? await Promise.all(params.tasks.map(async (t) => {
|
|
1497
1706
|
const startedAt = Date.now();
|
|
1498
|
-
const prepared =
|
|
1707
|
+
const prepared = rexPanes
|
|
1708
|
+
? await prepareRexOne(t.agent, t.task, t.cwd, t.timeout ?? params.timeout, t.solutionSpace)
|
|
1709
|
+
: appPanes
|
|
1710
|
+
? await prepareHerdrAppOne(t.agent, t.task, t.cwd, t.timeout ?? params.timeout, t.solutionSpace)
|
|
1711
|
+
: await prepareHerdrOne(t.agent, t.task, t.cwd, t.timeout ?? params.timeout, t.solutionSpace);
|
|
1499
1712
|
if ("error" in prepared) return { ok: false as const, error: prepared.error, startedAt };
|
|
1500
1713
|
return { ok: true as const, handle: prepared.handle, timeoutMs: prepared.timeoutMs, startedAt: prepared.startedAt };
|
|
1501
1714
|
}))
|
|
1502
1715
|
: undefined;
|
|
1503
1716
|
if (herdrPrepared) {
|
|
1504
1717
|
const cancelAll = () => {
|
|
1505
|
-
for (const p of herdrPrepared) if (p.ok)
|
|
1718
|
+
for (const p of herdrPrepared) if (p.ok) cancelPane(p.handle);
|
|
1506
1719
|
};
|
|
1507
1720
|
if (signal) {
|
|
1508
1721
|
if (signal.aborted) cancelAll();
|
|
@@ -1551,7 +1764,7 @@ ${lines.join("\n")}`;
|
|
|
1551
1764
|
// Skip if already aborted by sibling failure or parent abort
|
|
1552
1765
|
if (parallelController.signal.aborted) {
|
|
1553
1766
|
const preparedSkip = herdrPrepared?.[index];
|
|
1554
|
-
if (preparedSkip?.ok)
|
|
1767
|
+
if (preparedSkip?.ok) cancelPane(preparedSkip.handle);
|
|
1555
1768
|
// Sibling/parent cancellation surfaces as "aborted", not "error" —
|
|
1556
1769
|
// render and /subagent history key off the stopReason.
|
|
1557
1770
|
const skipReason =
|
|
@@ -1571,15 +1784,33 @@ ${lines.join("\n")}`;
|
|
|
1571
1784
|
const prepared = herdrPrepared?.[index];
|
|
1572
1785
|
const result = prepared
|
|
1573
1786
|
? prepared.ok
|
|
1574
|
-
? await
|
|
1787
|
+
? await (rexPanes
|
|
1788
|
+
? executeRexTask(prepared.handle as RexHandle, {
|
|
1575
1789
|
onState: (state) => threadStore.updateProgress(
|
|
1576
1790
|
parallelThreads[index].id,
|
|
1577
|
-
herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs),
|
|
1791
|
+
herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs, "rex"),
|
|
1578
1792
|
),
|
|
1579
|
-
|
|
1580
|
-
// feeds parallelController via onParentAbort).
|
|
1793
|
+
advisorWaitMs: subSettings.advisorWaitSecs * 1000,
|
|
1581
1794
|
signal: parallelController.signal,
|
|
1582
1795
|
})
|
|
1796
|
+
: appPanes
|
|
1797
|
+
? executeHerdrAppTask(prepared.handle as HerdrAppHandle, {
|
|
1798
|
+
onState: (state) => threadStore.updateProgress(
|
|
1799
|
+
parallelThreads[index].id,
|
|
1800
|
+
herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs, "herdr-app"),
|
|
1801
|
+
),
|
|
1802
|
+
advisorWaitMs: subSettings.advisorWaitSecs * 1000,
|
|
1803
|
+
signal: parallelController.signal,
|
|
1804
|
+
})
|
|
1805
|
+
: executeHerdrTask(prepared.handle as HerdrHandle, {
|
|
1806
|
+
onState: (state) => threadStore.updateProgress(
|
|
1807
|
+
parallelThreads[index].id,
|
|
1808
|
+
herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs),
|
|
1809
|
+
),
|
|
1810
|
+
// Covers abortOnFailure AND parent abort (parent abort
|
|
1811
|
+
// feeds parallelController via onParentAbort).
|
|
1812
|
+
signal: parallelController.signal,
|
|
1813
|
+
}))
|
|
1583
1814
|
: makeErrorResult(t.agent, t.task, prepared.error)
|
|
1584
1815
|
: await runOne(
|
|
1585
1816
|
t.agent, t.task, t.cwd,
|
|
@@ -1672,7 +1903,13 @@ ${lines.join("\n")}`;
|
|
|
1672
1903
|
if (ctx.mode === "tui") widget.ensureWidget(ctx);
|
|
1673
1904
|
// A foreground rerun of a pinned-sdk / disabled / unprobed call would
|
|
1674
1905
|
// also run in-process — only advise when it would really delegate.
|
|
1675
|
-
const hint = backgroundHerdrHint(
|
|
1906
|
+
const hint = backgroundHerdrHint(
|
|
1907
|
+
await wouldHerdrDelegate(params.runner, (ctx as any).settings?.subagent, herdrCli.exec) ||
|
|
1908
|
+
(params.runner === undefined && herdrAppEnvDetected() && !herdrAppDisabled((ctx as any).settings?.subagent)
|
|
1909
|
+
&& await probeHerdrAppBinary(herdrAppCli.exec)) ||
|
|
1910
|
+
(params.runner === undefined && rexEnvDetected() && !rexDisabled((ctx as any).settings?.subagent)
|
|
1911
|
+
&& await probeRexBinary(rexCli.exec)),
|
|
1912
|
+
);
|
|
1676
1913
|
const autoNote = autoBackground
|
|
1677
1914
|
? "Dispatch: the task classifier chose background (long/self-contained) — pass runner or background explicitly to override."
|
|
1678
1915
|
: "";
|
|
@@ -1693,7 +1930,8 @@ ${lines.join("\n")}`;
|
|
|
1693
1930
|
const historyId = makeForegroundHistoryId(thread.createdAt);
|
|
1694
1931
|
recordForegroundStart(historyId, params.agent, params.task, thread.createdAt);
|
|
1695
1932
|
const result = herdrActive
|
|
1696
|
-
? await
|
|
1933
|
+
? await startPaneOne(
|
|
1934
|
+
runnerKind as "herdr" | "herdr-app" | "rex",
|
|
1697
1935
|
params.agent, params.task, params.cwd,
|
|
1698
1936
|
signal, params.timeout,
|
|
1699
1937
|
(progress) => threadStore.updateProgress(thread.id, progress),
|
|
@@ -1936,7 +2174,8 @@ ${lines.join("\n")}`;
|
|
|
1936
2174
|
new Text(
|
|
1937
2175
|
fg("muted", `─── Step ${r.exitCode !== -1 ? "" : "?"}: `) +
|
|
1938
2176
|
fg(resolveAgentColor(r.agent), r.agent) +
|
|
1939
|
-
` ${stepIcon}
|
|
2177
|
+
` ${stepIcon}` +
|
|
2178
|
+
(r.bestEffort ? ` ${fg("warning", "⚠ best-effort pane capture")}` : ""),
|
|
1940
2179
|
0,
|
|
1941
2180
|
0,
|
|
1942
2181
|
),
|
|
@@ -2073,6 +2312,215 @@ ${lines.join("\n")}`;
|
|
|
2073
2312
|
// herdr control tool — main-session oversight of delegated pane agents
|
|
2074
2313
|
// ---------------------------------------------------------------------------
|
|
2075
2314
|
|
|
2315
|
+
/**
|
|
2316
|
+
* herdr-app flavor of the control tool. Same action surface, different
|
|
2317
|
+
* plumbing: `herdr-app do` for layout (focus/close-tab) and `hc` for the
|
|
2318
|
+
* terminal itself (status/read/prompt/cancel). Handles identify their pane
|
|
2319
|
+
* by hc ADDRESS ("t7"); `name` (the allocated label) is accepted too.
|
|
2320
|
+
*/
|
|
2321
|
+
async function runAppControl(
|
|
2322
|
+
action: string,
|
|
2323
|
+
name: string,
|
|
2324
|
+
params: { text?: string; lines?: number; wait?: boolean; timeout?: number },
|
|
2325
|
+
toolResult: (text: string, isError?: boolean) => { content: { type: "text"; text: string }[]; isError: boolean; details: Record<string, unknown> },
|
|
2326
|
+
) {
|
|
2327
|
+
const entry = findHerdrAppAgent(name);
|
|
2328
|
+
const address = entry?.address ?? name;
|
|
2329
|
+
const delegated = Boolean(entry);
|
|
2330
|
+
const refuseUndelegated = (verb: string) =>
|
|
2331
|
+
toolResult(`"${name}" was not delegated by this session — refusing to ${verb} an agent this session did not start. If this pane predates a /reload-runtime, interrupt or close it manually (hc interrupt <addr>; \`herdr-app ls\` lists tabs).`, true);
|
|
2332
|
+
switch (action) {
|
|
2333
|
+
case "list": {
|
|
2334
|
+
const entries = getHerdrAppRegistry();
|
|
2335
|
+
if (entries.length === 0) {
|
|
2336
|
+
return toolResult("No herdr-app-delegated agents this session. Delegation goes to app panes automatically while pi runs in a Herdr app terminal (or with subagent runner).");
|
|
2337
|
+
}
|
|
2338
|
+
const lines: string[] = [];
|
|
2339
|
+
for (const e of entries) {
|
|
2340
|
+
const info = await getAppTerminal(e.address, herdrAppCli.exec);
|
|
2341
|
+
lines.push(`- ${e.name} · ${e.agentType} · ${info?.status ?? "unknown"} · tab ${e.tabName} / ${e.address} — ${e.task.slice(0, 60)}${e.task.length > 60 ? "…" : ""}`);
|
|
2342
|
+
}
|
|
2343
|
+
return toolResult(`Delegated herdr-app agents (${entries.length}):\n${lines.join("\n")}`);
|
|
2344
|
+
}
|
|
2345
|
+
case "status": {
|
|
2346
|
+
const info = await getAppTerminal(address, herdrAppCli.exec);
|
|
2347
|
+
if (!info) return toolResult(`No herdr-app terminal "${name}".`, true);
|
|
2348
|
+
return toolResult(`${name}: ${info.status} (${info.state}; tab ${entry?.tabName ?? "?"}${entry ? ` / ${info.address}` : ""}${info.cwd ? `, cwd ${info.cwd}` : ""})`);
|
|
2349
|
+
}
|
|
2350
|
+
case "read": {
|
|
2351
|
+
const res = await readAppTerminal(address, params.lines ?? 120, herdrAppCli.exec);
|
|
2352
|
+
if (!res.ok) return toolResult(`hc read failed: ${res.text}`, true);
|
|
2353
|
+
return toolResult(
|
|
2354
|
+
res.text.trim() || (entry?.readOnly
|
|
2355
|
+
? "(no readable output — the agent may be rendering on the alternate screen; prompt it and it will reply inline — it has read-only tools and cannot write files)"
|
|
2356
|
+
: "(no readable output — the agent may be rendering on the alternate screen; prompt it to write its report to a file)"),
|
|
2357
|
+
);
|
|
2358
|
+
}
|
|
2359
|
+
case "prompt": {
|
|
2360
|
+
if (!params.text) return toolResult('Missing text for action "prompt".', true);
|
|
2361
|
+
if (Buffer.byteLength(params.text, "utf8") > HERDR_TASK_BUDGET) {
|
|
2362
|
+
return toolResult(`Prompt exceeds the ${HERDR_TASK_BUDGET}-byte budget (delivery wrapper included) — shorten it.`, true);
|
|
2363
|
+
}
|
|
2364
|
+
if (!delegated) return refuseUndelegated("prompt");
|
|
2365
|
+
const text = wrapAppTaskPrompt(params.text, entry!.resultFile, entry!.readOnly);
|
|
2366
|
+
if (!params.wait) {
|
|
2367
|
+
const sent = await sendAppPrompt(address, text, herdrAppCli.exec);
|
|
2368
|
+
return toolResult(sent.ok ? `Prompt submitted to ${name}.` : `hc send failed: ${sent.error}`, !sent.ok);
|
|
2369
|
+
}
|
|
2370
|
+
const timeoutMs = Math.min(params.timeout ?? 120_000, MAX_TIMEOUT_MS);
|
|
2371
|
+
const stampBefore = await fs.stat(entry!.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
|
|
2372
|
+
const outcome = await promptAppAndWait({ address, text, timeoutMs, exec: herdrAppCli.exec });
|
|
2373
|
+
if (outcome.error) return toolResult(`${name}: ${outcome.error} (state: ${outcome.state})`, true);
|
|
2374
|
+
const collected = await collectAppResult({ handle: entry!, exec: herdrAppCli.exec });
|
|
2375
|
+
if (collected.source === "file") {
|
|
2376
|
+
const stampAfter = await fs.stat(entry!.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
|
|
2377
|
+
if (stampAfter === stampBefore) {
|
|
2378
|
+
return toolResult(`${name}: ${outcome.state} (no new report file content for this follow-up)`);
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
return toolResult(`${name}: ${outcome.state}${collected.output ? `\n\n${collected.output}` : ""}`);
|
|
2382
|
+
}
|
|
2383
|
+
case "cancel": {
|
|
2384
|
+
if (!delegated) return refuseUndelegated("cancel");
|
|
2385
|
+
await cancelAppAgent(address, herdrAppCli.exec);
|
|
2386
|
+
return toolResult(`Interrupted ${name} (hc interrupt, plus hc kill if it was still working).`);
|
|
2387
|
+
}
|
|
2388
|
+
case "focus": {
|
|
2389
|
+
const tabId = entry?.tabId;
|
|
2390
|
+
if (!tabId) return toolResult(`No delegated herdr-app agent named "${name}" (focus needs a tab this session knows).`, true);
|
|
2391
|
+
const res = await focusAppTab(tabId, herdrAppCli.exec);
|
|
2392
|
+
return toolResult(res.ok ? `Focused tab ${entry!.tabName} (${tabId}).` : `herdr-app tab.select failed: ${res.error}`, !res.ok);
|
|
2393
|
+
}
|
|
2394
|
+
case "close-tab": {
|
|
2395
|
+
if (!delegated) return toolResult(`"${name}" was not delegated by this session — refusing to close tabs this session did not create.`, true);
|
|
2396
|
+
if (!entry!.tabCreatedHere) {
|
|
2397
|
+
return toolResult(`"${name}" runs in a tab that existed before this session dispatched to it (label match) — reusing it for dispatch, but refusing to close it.`, true);
|
|
2398
|
+
}
|
|
2399
|
+
const { siblings: busy, self: selfBusy } = await appTabCloseBlockers(entry!, herdrAppCli.exec);
|
|
2400
|
+
if (busy.length > 0) {
|
|
2401
|
+
return toolResult(`Refusing to close tab ${entry!.tabName}: sibling agent(s) still busy or unverifiable: ${busy.join(", ")}. Cancel them first (action "cancel") or wait until they settle.`, true);
|
|
2402
|
+
}
|
|
2403
|
+
if (selfBusy) {
|
|
2404
|
+
return toolResult(`"${name}" is still ${selfBusy} — cancel it first (action "cancel") or wait for it to settle before closing its tab.`, true);
|
|
2405
|
+
}
|
|
2406
|
+
const res = await closeAppTab(entry!.tabId, herdrAppCli.exec);
|
|
2407
|
+
if (!res.ok) return toolResult(`herdr-app tab.close failed: ${res.error}`, true);
|
|
2408
|
+
forgetHerdrAppTab(entry!.tabName);
|
|
2409
|
+
return toolResult(`Closed tab ${entry!.tabName} (all its panes).`);
|
|
2410
|
+
}
|
|
2411
|
+
case "forget": {
|
|
2412
|
+
if (!delegated) return toolResult(`"${name}" was not delegated by this session — nothing to forget.`, true);
|
|
2413
|
+
forgetHerdrAppTab(entry!.tabName);
|
|
2414
|
+
return toolResult(`Forgot ${name} (registry entry only — app tabs/terminals untouched).`);
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
return toolResult(`Unknown action "${action}".`, true);
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
/** Control-tool handler for Rex-delegated agents (runAppControl's sibling). */
|
|
2421
|
+
async function runRexControl(
|
|
2422
|
+
action: string,
|
|
2423
|
+
name: string,
|
|
2424
|
+
params: { text?: string; lines?: number; wait?: boolean; timeout?: number },
|
|
2425
|
+
toolResult: (text: string, isError?: boolean) => { content: { type: "text"; text: string }[]; isError: boolean; details: Record<string, unknown> },
|
|
2426
|
+
) {
|
|
2427
|
+
const entry = findRexAgent(name);
|
|
2428
|
+
const address = entry?.address ?? name;
|
|
2429
|
+
const delegated = Boolean(entry);
|
|
2430
|
+
const refuseUndelegated = (verb: string) =>
|
|
2431
|
+
toolResult(`"${name}" was not delegated by this session — refusing to ${verb} an agent this session did not start. If this pane predates a /reload-runtime, interrupt or close it manually (rex block close <blockId>; \`rex block ls --json\` lists blocks).`, true);
|
|
2432
|
+
switch (action) {
|
|
2433
|
+
case "list": {
|
|
2434
|
+
const entries = getRexRegistry();
|
|
2435
|
+
if (entries.length === 0) {
|
|
2436
|
+
return toolResult("No rex-delegated agents this session. Delegation goes to rex panes automatically while pi runs in a Rex terminal (or with subagent runner).");
|
|
2437
|
+
}
|
|
2438
|
+
const lines: string[] = [];
|
|
2439
|
+
for (const e of entries) {
|
|
2440
|
+
const info = await getRexTerminalState(e.address, rexCli.exec);
|
|
2441
|
+
lines.push(`- ${e.name} · ${e.agentType} · ${info?.status ?? "unknown"} · window ${e.tabId} / ${e.address} — ${e.task.slice(0, 60)}${e.task.length > 60 ? "…" : ""}`);
|
|
2442
|
+
}
|
|
2443
|
+
return toolResult(`Delegated rex agents (${entries.length}):\n${lines.join("\n")}`);
|
|
2444
|
+
}
|
|
2445
|
+
case "status": {
|
|
2446
|
+
const info = await getRexTerminalState(address, rexCli.exec);
|
|
2447
|
+
if (!info) return toolResult(`No rex terminal "${name}".`, true);
|
|
2448
|
+
return toolResult(`${name}: ${info.status} (${info.state}; window ${entry?.tabId ?? "?"}${entry ? ` / ${info.address}` : ""}${info.cwd ? `, cwd ${info.cwd}` : ""})`);
|
|
2449
|
+
}
|
|
2450
|
+
case "read": {
|
|
2451
|
+
const lines = Math.min(Math.max(Math.trunc(params.lines ?? 120), 1), 1000);
|
|
2452
|
+
const res = await readRexBlock(address, rexCli.exec);
|
|
2453
|
+
if (!res.ok) return toolResult(`rex block call format failed: ${res.text}`, true);
|
|
2454
|
+
const tail = res.text.split("\n").slice(-lines).join("\n").trim();
|
|
2455
|
+
return toolResult(
|
|
2456
|
+
tail || (entry?.readOnly
|
|
2457
|
+
? "(no readable output — the agent may be rendering on the alternate screen; prompt it and it will reply inline — it has read-only tools and cannot write files)"
|
|
2458
|
+
: "(no readable output — the agent may be rendering on the alternate screen; prompt it to write its report to a file)"),
|
|
2459
|
+
);
|
|
2460
|
+
}
|
|
2461
|
+
case "prompt": {
|
|
2462
|
+
if (!params.text) return toolResult('Missing text for action "prompt".', true);
|
|
2463
|
+
if (Buffer.byteLength(params.text, "utf8") > HERDR_TASK_BUDGET) {
|
|
2464
|
+
return toolResult(`Prompt exceeds the ${HERDR_TASK_BUDGET}-byte budget (delivery wrapper included) — shorten it.`, true);
|
|
2465
|
+
}
|
|
2466
|
+
if (!delegated) return refuseUndelegated("prompt");
|
|
2467
|
+
const text = wrapRexTaskPrompt(params.text, entry!.resultFile, entry!.readOnly);
|
|
2468
|
+
if (!params.wait) {
|
|
2469
|
+
const sent = await sendRexPrompt(address, text, rexCli.exec);
|
|
2470
|
+
return toolResult(sent.ok ? `Prompt submitted to ${name}.` : `rex block send failed: ${sent.error}`, !sent.ok);
|
|
2471
|
+
}
|
|
2472
|
+
const timeoutMs = Math.min(params.timeout ?? 120_000, MAX_TIMEOUT_MS);
|
|
2473
|
+
const stampBefore = await fs.stat(entry!.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
|
|
2474
|
+
const outcome = await promptRexAndWait({ address, text, timeoutMs, exec: rexCli.exec });
|
|
2475
|
+
if (outcome.error) return toolResult(`${name}: ${outcome.error} (state: ${outcome.state})`, true);
|
|
2476
|
+
const collected = await collectRexResult({ handle: entry!, exec: rexCli.exec });
|
|
2477
|
+
if (collected.source === "file") {
|
|
2478
|
+
const stampAfter = await fs.stat(entry!.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
|
|
2479
|
+
if (stampAfter === stampBefore) {
|
|
2480
|
+
// Follow-ups reuse the same report file: unchanged content is the
|
|
2481
|
+
// PREVIOUS run's report, not this prompt's answer.
|
|
2482
|
+
return toolResult(`${name}: ${outcome.state} (no new report file content for this follow-up)`);
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
return toolResult(`${name}: ${outcome.state}${collected.output ? `\n\n${collected.output}` : ""}`);
|
|
2486
|
+
}
|
|
2487
|
+
case "cancel": {
|
|
2488
|
+
if (!delegated) return refuseUndelegated("cancel");
|
|
2489
|
+
await cancelRexAgent(address, rexCli.exec);
|
|
2490
|
+
return toolResult(`Interrupted ${name} (esc, plus ctrl+c if it was still working).`);
|
|
2491
|
+
}
|
|
2492
|
+
case "focus": {
|
|
2493
|
+
const windowId = entry?.tabId;
|
|
2494
|
+
if (!windowId) return toolResult(`No delegated rex agent named "${name}" (focus needs a window this session knows).`, true);
|
|
2495
|
+
const res = await focusRexWindow(windowId, rexCli.exec);
|
|
2496
|
+
return toolResult(res.ok ? `Focused window ${windowId}.` : `rex focus failed: ${res.error}`, !res.ok);
|
|
2497
|
+
}
|
|
2498
|
+
case "close-tab": {
|
|
2499
|
+
if (!delegated) return toolResult(`"${name}" was not delegated by this session — refusing to close windows this session did not create.`, true);
|
|
2500
|
+
if (!entry!.tabCreatedHere) {
|
|
2501
|
+
return toolResult(`"${name}" runs in a window that existed before this session dispatched to it (label match) — reusing it for dispatch, but refusing to close it.`, true);
|
|
2502
|
+
}
|
|
2503
|
+
const { siblings: busy, self: selfBusy } = await rexWindowCloseBlockers(entry!, rexCli.exec);
|
|
2504
|
+
if (busy.length > 0) {
|
|
2505
|
+
return toolResult(`Refusing to close window ${entry!.tabId}: sibling agent(s) still busy or unverifiable: ${busy.join(", ")}. Cancel them first (action "cancel") or wait until they settle.`, true);
|
|
2506
|
+
}
|
|
2507
|
+
if (selfBusy) {
|
|
2508
|
+
return toolResult(`"${name}" is still ${selfBusy} — cancel it first (action "cancel") or wait for it to settle before closing its window.`, true);
|
|
2509
|
+
}
|
|
2510
|
+
const res = await closeRexWindow(entry!.tabId, rexCli.exec);
|
|
2511
|
+
if (!res.ok) return toolResult(`rex window close failed: ${res.error}`, true);
|
|
2512
|
+
forgetRexWindow(entry!.tabId);
|
|
2513
|
+
return toolResult(`Closed window ${entry!.tabId} (all its panes).`);
|
|
2514
|
+
}
|
|
2515
|
+
case "forget": {
|
|
2516
|
+
if (!delegated) return toolResult(`"${name}" was not delegated by this session — nothing to forget.`, true);
|
|
2517
|
+
forgetRexAgent(entry!.name);
|
|
2518
|
+
return toolResult(`Forgot ${name} (registry entry only — rex windows/blocks untouched).`);
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
return toolResult(`Unknown action "${action}".`, true);
|
|
2522
|
+
}
|
|
2523
|
+
|
|
2076
2524
|
const HerdrControlParams = Type.Object({
|
|
2077
2525
|
action: StringEnum(["list", "status", "read", "prompt", "cancel", "focus", "close-tab", "forget"] as const, {
|
|
2078
2526
|
description:
|
|
@@ -2093,15 +2541,15 @@ ${lines.join("\n")}`;
|
|
|
2093
2541
|
name: "herdr",
|
|
2094
2542
|
label: "Herdr",
|
|
2095
2543
|
description: [
|
|
2096
|
-
"Control agents this session delegated to
|
|
2544
|
+
"Control agents this session delegated to visible panes — herdr TUI (HERDR_ENV), herdr-app (HC_TERMINAL_ID), or rex (REX_SESSION; subagent delegation is automatic in all three).",
|
|
2097
2545
|
"Actions: list, status, read, prompt, cancel, focus, close-tab, forget.",
|
|
2098
2546
|
].join(" "),
|
|
2099
2547
|
parameters: HerdrControlParams,
|
|
2100
|
-
promptSnippet: "Control delegated
|
|
2548
|
+
promptSnippet: "Control delegated pane agents — herdr/rex (list/status/read/prompt/cancel/focus/close-tab/forget)",
|
|
2101
2549
|
promptGuidelines: [
|
|
2102
|
-
"Use for oversight of
|
|
2550
|
+
"Use for oversight of delegated subagents (herdr or rex): status/read to inspect, prompt to continue an agent's session, cancel to interrupt, focus to raise its tab/window, forget to drop a stale registry entry.",
|
|
2103
2551
|
"A blocked agent waits for human input — answer it in the pane directly, or cancel and re-delegate.",
|
|
2104
|
-
"prompt/cancel/forget only accept agents this session delegated and close-tab only tabs it created; status/read/focus can inspect any live
|
|
2552
|
+
"prompt/cancel/forget only accept agents this session delegated and close-tab only tabs/windows it created; status/read/focus can inspect any live agent.",
|
|
2105
2553
|
"read is best-effort: pi renders on the terminal's alternate screen, so finished reports may not be scrollback-visible (delegated tasks deliver via report files instead).",
|
|
2106
2554
|
],
|
|
2107
2555
|
async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
|
|
@@ -2110,17 +2558,22 @@ ${lines.join("\n")}`;
|
|
|
2110
2558
|
isError,
|
|
2111
2559
|
details: {},
|
|
2112
2560
|
});
|
|
2113
|
-
|
|
2114
|
-
|
|
2561
|
+
const tuiMode = herdrTuiEnvDetected();
|
|
2562
|
+
const appMode = !tuiMode && herdrAppEnvDetected();
|
|
2563
|
+
const rexMode = !tuiMode && !appMode && rexEnvDetected() && await probeRexBinary(rexCli.exec);
|
|
2564
|
+
if (!tuiMode && !appMode && !rexMode) {
|
|
2565
|
+
return toolResult("Not running inside a multiplexer: no HERDR_ENV (herdr TUI), no HC_TERMINAL_ID (herdr-app), and no REX_SESSION (rex). Start pi inside a herdr pane, a Herdr app terminal, or a Rex terminal to delegate agents to visible panes.", true);
|
|
2115
2566
|
}
|
|
2116
2567
|
if (herdrDisabled(undefined)) {
|
|
2117
|
-
// Delegated child session (PI_SUBAGENT_HERDR=off): no
|
|
2118
|
-
return toolResult("
|
|
2568
|
+
// Delegated child session (PI_SUBAGENT_HERDR=off): no pane control.
|
|
2569
|
+
return toolResult("Pane-delegation control is disabled in this session (PI_SUBAGENT_HERDR=off child guard).", true);
|
|
2119
2570
|
}
|
|
2120
2571
|
if (params.action !== "list" && !params.name) {
|
|
2121
|
-
return toolResult(`Missing name for action "${params.action}". Use
|
|
2572
|
+
return toolResult(`Missing name for action "${params.action}". Use an agent name from action "list" (e.g. scout-1).`, true);
|
|
2122
2573
|
}
|
|
2123
2574
|
const name = params.name!;
|
|
2575
|
+
if (appMode) return runAppControl(params.action, name, params, toolResult);
|
|
2576
|
+
if (rexMode) return runRexControl(params.action, name, params, toolResult);
|
|
2124
2577
|
// Mutating actions are scoped to agents this session delegated —
|
|
2125
2578
|
// the model must not drive (or kill) panes it never spawned.
|
|
2126
2579
|
if ((params.action === "prompt" || params.action === "cancel") && !isDelegatedHerdrAgent(name)) {
|