ceulen 0.26.1 → 0.27.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.
@@ -67,6 +67,7 @@ import {
67
67
  } from "./lib/security.ts";
68
68
  import {
69
69
  aggregateUsage,
70
+ expandKeyLabel,
70
71
  formatUsageStats,
71
72
  renderSingleResult,
72
73
  } from "./lib/render.ts";
@@ -87,10 +88,33 @@ import { startBackgroundTask,
87
88
  clearBackgroundTasks,
88
89
  } from "./lib/background.ts";
89
90
  import { parseStructuredResult } from "./lib/result.ts";
91
+ import { formatChainReport } from "./lib/render.ts";
90
92
  import { skillsRoot } from "../../lib/skill-path.js";
91
93
  import { isChildSession } from "../../lib/child-session.js";
92
94
  import { appendHistory, readHistory, markInterruptedOnRestart, trimHistory, getHistoryPath } from "./lib/history.ts";
93
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";
94
118
  /** Keep-alive cadence for herdr delegations (test seam: shorten to assert). */
95
119
  export const herdrHeartbeat = { intervalMs: 30_000 };
96
120
  import {
@@ -103,7 +127,7 @@ import {
103
127
  getAgentInfo,
104
128
  herdrDisabled,
105
129
  getHerdrRegistry,
106
- herdrEnvDetected,
130
+ herdrTuiEnvDetected,
107
131
  herdrTabCloseBlockers,
108
132
  isDelegatedHerdrAgent,
109
133
  listHerdrAgents,
@@ -125,6 +149,9 @@ import {
125
149
  // Constants
126
150
  // ---------------------------------------------------------------------------
127
151
 
152
+ /** Visible-pane delegation backend for one dispatch. */
153
+ type RunnerKind = "sdk" | "herdr" | "herdr-app";
154
+
128
155
  // ---------------------------------------------------------------------------
129
156
  // Helpers
130
157
  // ---------------------------------------------------------------------------
@@ -213,7 +240,7 @@ const SubagentParams = Type.Object({
213
240
  instructions: Type.Optional(Type.String({ description: "Bounded repository/task instructions passed to each child (max 16 KB)" })),
214
241
  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'." })),
215
242
  runner: Type.Optional(StringEnum(["sdk", "herdr"] as const, {
216
- description: 'Execution backend: "sdk" (in-process, lean) or "herdr" (visible interactive pi panes in a herdr session; one tab per agent type, one pane per instance). Default: herdr when pi runs inside herdr, otherwise sdk.',
243
+ 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), herdr-app inside a Herdr app/core terminal (HC_TERMINAL_ID), otherwise sdk.',
217
244
  })),
218
245
  abortOnFailure: Type.Optional(Type.Boolean({ description: "In parallel mode, cancel remaining tasks when one fails. Default: false.", default: false })),
219
246
  });
@@ -644,6 +671,27 @@ ${lines.join("\n")}`;
644
671
  return found?.color ? AGENT_TO_THEME_COLOR[found.color] : "accent";
645
672
  };
646
673
 
674
+ /**
675
+ * Effective runner across BOTH visible-pane backends.
676
+ *
677
+ * herdr TUI (`HERDR_ENV=1`, `herdr` CLI) keeps its exact existing semantics
678
+ * (lib/herdr.ts resolveEffectiveRunner: explicit params, errors, probe).
679
+ * herdr-app (`HC_TERMINAL_ID`, `herdr-app` + `hc`) is the AUTO fallback:
680
+ * when no explicit runner was named and the TUI path did not claim the call,
681
+ * delegate to app panes. An explicit `runner:"herdr"` never silently
682
+ * re-routes to the app — its "not running inside herdr" error stays.
683
+ */
684
+ async function resolveRunner(
685
+ requested: "sdk" | "herdr" | undefined,
686
+ subagentSettings: { herdr?: unknown } | undefined,
687
+ ): Promise<{ runner: RunnerKind; error?: string }> {
688
+ const tui = await resolveEffectiveRunner(requested, subagentSettings, herdrCli.exec);
689
+ if (tui.runner === "herdr" || tui.error || requested !== undefined) return tui;
690
+ if (!herdrAppEnvDetected() || herdrAppDisabled(subagentSettings)) return tui;
691
+ if (!await probeHerdrAppBinary(herdrAppCli.exec)) return tui;
692
+ return { runner: "herdr-app" };
693
+ }
694
+
647
695
  pi.registerTool({
648
696
  name: "subagent",
649
697
  label: "Subagent",
@@ -664,9 +712,9 @@ ${lines.join("\n")}`;
664
712
  "For background single tasks use background:true — you will be notified on completion; DO NOT poll or sleep.",
665
713
  '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.',
666
714
  "Set solutionSpace when a task's openness isn't obvious from its text — it feeds tier/thinking routing.",
667
- "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.",
715
+ "Inside herdr (TUI or app), 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.",
668
716
  "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).",
669
- `Runner: "sdk" runs agents in-process (lean, default outside herdr); "herdr" delegates to visible interactive pi panes in a herdr session (one tab per agent type, one pane per instance) — default when pi runs inside herdr. herdr children share the working tree and skip worktree isolation; background:true always uses the sdk runner.`,
717
+ `Runner: "sdk" runs agents in-process (lean, default outside herdr); "herdr" delegates to visible interactive pi panes (one tab per agent type, one pane per instance) — the default inside the herdr TUI (HERDR_ENV) and inside a Herdr app/core terminal (HC_TERMINAL_ID, via herdr-app + hc). Pane children share the working tree and skip worktree isolation; background:true always uses the sdk runner.`,
670
718
  "Use /subagent list to list all available agents, /subagent <name> for agent details, /subagent @role for role detail.",
671
719
  ],
672
720
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
@@ -701,11 +749,7 @@ ${lines.join("\n")}`;
701
749
  (params.operation !== undefined || params.background === true);
702
750
  const runnerResolved = skipRunnerResolution
703
751
  ? { runner: "sdk" as const }
704
- : await resolveEffectiveRunner(
705
- params.runner,
706
- (ctx as any).settings?.subagent ?? {},
707
- herdrCli.exec,
708
- );
752
+ : await resolveRunner(params.runner, (ctx as any).settings?.subagent ?? {});
709
753
  if (runnerResolved.error) {
710
754
  return {
711
755
  content: [{ type: "text", text: runnerResolved.error }],
@@ -715,7 +759,8 @@ ${lines.join("\n")}`;
715
759
  }
716
760
  // background:true always runs the in-process SDK runner (herdr tasks are
717
761
  // foreground) — keep the details stamp honest.
718
- const herdrActive = runnerResolved.runner === "herdr" && !params.background;
762
+ const runnerKind: RunnerKind = params.background ? "sdk" : runnerResolved.runner;
763
+ const herdrActive = runnerKind !== "sdk";
719
764
 
720
765
  // Worktree isolation / merge:"3way" is an SDK-runner feature — herdr
721
766
  // children share the parent's working tree, so a silent drop would turn
@@ -726,7 +771,7 @@ ${lines.join("\n")}`;
726
771
  .some((n) => agents.find((a) => a.name === n)?.sandbox === "worktree");
727
772
  if (herdrActive && (requestedMerge || worktreeAgentRequested)) {
728
773
  return {
729
- 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" : ""}.` }],
774
+ content: [{ type: "text", text: `Worktree isolation${requestedMerge ? " / merge:\"3way\"" : ""} requires runner:"sdk" — herdr/herdr-app children share the parent's working tree. Re-run with runner:"sdk"${requestedMerge ? " or drop merge" : ""}.` }],
730
775
  details: { mode: "single" as const, agentScope, projectAgentsDir: discovery.projectAgentsDir, results: [] },
731
776
  isError: true,
732
777
  };
@@ -1028,11 +1073,11 @@ ${lines.join("\n")}`;
1028
1073
  };
1029
1074
  }
1030
1075
 
1031
- // Helper: widget progress snapshot from a herdr lifecycle state.
1032
- function herdrProgress(agentName: string, task: string, state: string, startedAt: number, timeoutMs: number): SubAgentProgress {
1076
+ // Helper: widget progress snapshot from a pane lifecycle state.
1077
+ function herdrProgress(agentName: string, task: string, state: string, startedAt: number, timeoutMs: number, kind: "herdr" | "herdr-app" = "herdr"): SubAgentProgress {
1033
1078
  const now = Date.now();
1034
1079
  return {
1035
- label: `herdr: ${state}`,
1080
+ label: `${kind}: ${state}`,
1036
1081
  at: now,
1037
1082
  elapsedMs: now - startedAt,
1038
1083
  inactivityDeadline: now + timeoutMs,
@@ -1086,17 +1131,26 @@ ${lines.join("\n")}`;
1086
1131
  };
1087
1132
  }
1088
1133
 
1089
- // Helper (herdr runner): validate + create topology + start the child pi,
1090
- // without prompting — so parallel dispatch can materialise every pane
1091
- // up front before any work starts.
1092
- async function prepareHerdrOne(
1134
+ /** Shared prelude for BOTH visible-pane backends: validate the agent,
1135
+ * route model+thinking, resolve the lifetime cap and the safe cwd.
1136
+ * Keeps the TUI and herdr-app prepares from drifting apart. */
1137
+ async function resolvePaneDispatch(
1093
1138
  agentName: string,
1094
1139
  task: string,
1095
1140
  cwd: string | undefined,
1096
1141
  timeoutMs: number | undefined,
1097
1142
  solutionSpace?: string,
1098
1143
  verdict?: RoutingVerdict,
1099
- ): Promise<{ handle: HerdrHandle; timeoutMs: number; startedAt: number } | { error: string }> {
1144
+ ): Promise<{
1145
+ agentType: string;
1146
+ systemPrompt: string;
1147
+ model: string;
1148
+ thinking?: string;
1149
+ tools?: string[];
1150
+ readOnly: boolean;
1151
+ cwd: string;
1152
+ timeoutMs: number;
1153
+ } | { error: string }> {
1100
1154
  const agent = agents.find((a) => a.name === agentName);
1101
1155
  if (!agent) return { error: `Unknown agent: "${agentName}".` };
1102
1156
  const { chain: agentChain, defaultThinking, error: chainError } = await routedChain(agent, task, solutionSpace, verdict);
@@ -1105,7 +1159,7 @@ ${lines.join("\n")}`;
1105
1159
  if (!resolved.model) {
1106
1160
  return { error: `No model resolved for agent "${agentName}" (tried: ${resolved.attempted.join(", ") || "none"}).` };
1107
1161
  }
1108
- // herdr children run full pi — they need SOME lifetime cap so an
1162
+ // Pane children run full pi — they need SOME lifetime cap so an
1109
1163
  // unattended pane can't run forever. The IDLE window is NOT a lifetime
1110
1164
  // cap (live incident 2026-10-06: a healthy 13-min chapter write was
1111
1165
  // abandoned at the default 3-min idle window — the pane kept working,
@@ -1115,33 +1169,91 @@ ${lines.join("\n")}`;
1115
1169
  const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, idleTimeoutMins: subSettings.idleTimeoutMins, hardTimeoutMins: subSettings.hardTimeoutMins });
1116
1170
  if (timeouts.error) return { error: timeouts.error };
1117
1171
  const hardTimeoutMs = timeouts.hardTimeoutMs ?? MAX_TIMEOUT_MS;
1118
- if (!hardTimeoutMs) return { error: "Invalid herdr timeout configuration." };
1172
+ if (!hardTimeoutMs) return { error: "Invalid pane timeout configuration." };
1119
1173
  const safe = resolveSafeCwd({ workspaceRoot, childCwd: cwd, allowExternalCwd });
1120
1174
  if (safe.error) return { error: safe.error };
1121
- const startedAt = Date.now();
1122
1175
  const systemPrompt = params.instructions
1123
1176
  ? `${agent.systemPrompt}\n\n## Task Contract\n${params.instructions.slice(0, MAX_INSTRUCTIONS_LENGTH)}`
1124
1177
  : agent.systemPrompt;
1178
+ return {
1179
+ agentType: agent.name,
1180
+ systemPrompt,
1181
+ model: `${resolved.model.provider}/${resolved.model.id}`,
1182
+ thinking: agentChain.thinkingByCandidate.get(resolved.matchedCandidate ?? "") ?? defaultThinking,
1183
+ tools: agent.tools,
1184
+ readOnly: agent.sandbox === "read-only",
1185
+ cwd: safe.path,
1186
+ timeoutMs: hardTimeoutMs,
1187
+ };
1188
+ }
1189
+
1190
+ // Helper (herdr runner): validate + create topology + start the child pi,
1191
+ // without prompting — so parallel dispatch can materialise every pane
1192
+ // up front before any work starts.
1193
+ async function prepareHerdrOne(
1194
+ agentName: string,
1195
+ task: string,
1196
+ cwd: string | undefined,
1197
+ timeoutMs: number | undefined,
1198
+ solutionSpace?: string,
1199
+ verdict?: RoutingVerdict,
1200
+ ): Promise<{ handle: HerdrHandle; timeoutMs: number; startedAt: number } | { error: string }> {
1201
+ const plan = await resolvePaneDispatch(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
1202
+ if ("error" in plan) return { error: plan.error };
1203
+ const startedAt = Date.now();
1125
1204
  try {
1126
1205
  const handle = await prepareHerdrTask({
1127
- agentType: agent.name,
1128
- systemPrompt,
1206
+ agentType: plan.agentType,
1207
+ systemPrompt: plan.systemPrompt,
1208
+ task,
1209
+ cwd: plan.cwd,
1210
+ model: plan.model,
1211
+ thinking: plan.thinking,
1212
+ tools: plan.tools,
1213
+ readOnly: plan.readOnly,
1214
+ timeoutMs: plan.timeoutMs,
1215
+ });
1216
+ return { handle, timeoutMs: plan.timeoutMs, startedAt };
1217
+ } catch (err) {
1218
+ return { error: err instanceof Error ? err.message : String(err) };
1219
+ }
1220
+ }
1221
+
1222
+ // Helper (herdr-app runner): the same prelude, delegated to app panes.
1223
+ async function prepareHerdrAppOne(
1224
+ agentName: string,
1225
+ task: string,
1226
+ cwd: string | undefined,
1227
+ timeoutMs: number | undefined,
1228
+ solutionSpace?: string,
1229
+ verdict?: RoutingVerdict,
1230
+ ): Promise<{ handle: HerdrAppHandle; timeoutMs: number; startedAt: number } | { error: string }> {
1231
+ const plan = await resolvePaneDispatch(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
1232
+ if ("error" in plan) return { error: plan.error };
1233
+ const startedAt = Date.now();
1234
+ try {
1235
+ const handle = await prepareHerdrAppTask({
1236
+ agentType: plan.agentType,
1237
+ systemPrompt: plan.systemPrompt,
1129
1238
  task,
1130
- cwd: safe.path,
1131
- model: `${resolved.model.provider}/${resolved.model.id}`,
1132
- thinking: agentChain.thinkingByCandidate.get(resolved.matchedCandidate ?? "") ?? defaultThinking,
1133
- tools: agent.tools,
1134
- readOnly: agent.sandbox === "read-only",
1135
- timeoutMs: hardTimeoutMs,
1239
+ cwd: plan.cwd,
1240
+ model: plan.model,
1241
+ thinking: plan.thinking,
1242
+ tools: plan.tools,
1243
+ readOnly: plan.readOnly,
1244
+ timeoutMs: plan.timeoutMs,
1136
1245
  });
1137
- return { handle, timeoutMs: hardTimeoutMs, startedAt };
1246
+ return { handle, timeoutMs: plan.timeoutMs, startedAt };
1138
1247
  } catch (err) {
1139
1248
  return { error: err instanceof Error ? err.message : String(err) };
1140
1249
  }
1141
1250
  }
1142
1251
 
1143
- // Helper (herdr runner): full delegation (prepare + prompt + collect).
1144
- async function startHerdrOne(
1252
+ // Helper (herdr + herdr-app runners): full delegation (prepare + prompt +
1253
+ // collect). Both backends differ only in prepare/execute/cancel/label, so
1254
+ // one flow keeps their abort + keep-alive semantics identical.
1255
+ async function startPaneOne(
1256
+ kind: "herdr" | "herdr-app",
1145
1257
  agentName: string,
1146
1258
  task: string,
1147
1259
  cwd: string | undefined,
@@ -1154,9 +1266,14 @@ ${lines.join("\n")}`;
1154
1266
  solutionSpace?: string,
1155
1267
  verdict?: RoutingVerdict,
1156
1268
  ): Promise<SubAgentResult> {
1157
- const prepared = await prepareHerdrOne(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
1269
+ const app = kind === "herdr-app";
1270
+ const prepared = app
1271
+ ? await prepareHerdrAppOne(agentName, task, cwd, timeoutMs, solutionSpace, verdict)
1272
+ : await prepareHerdrOne(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
1158
1273
  if ("error" in prepared) return makeErrorResult(agentName, task, prepared.error);
1159
- const { handle, startedAt } = prepared;
1274
+ const { startedAt } = prepared;
1275
+ // Narrowing the union by `app` keeps every later access type-safe.
1276
+ const handle = prepared.handle as HerdrAppHandle & HerdrHandle;
1160
1277
  // Keep-alive parity with the SDK path: a long pane run must emit
1161
1278
  // onUpdate traffic or the host may idle-abort the tool call.
1162
1279
  const stopHeartbeat = onUpdate ? startHeartbeat(() => {
@@ -1164,29 +1281,41 @@ ${lines.join("\n")}`;
1164
1281
  onUpdate({ content: [{ type: "text", text: "" }], details: heartbeatDetails?.() ?? makeDetails("single")([]) });
1165
1282
  widget.requestRender();
1166
1283
  }, herdrHeartbeat.intervalMs) : undefined;
1284
+ const paneRef = kind === "herdr-app" ? handle.address : handle.name;
1285
+ const progress = (state: string) => onActivity?.(
1286
+ herdrProgress(handle.agentType, task, state, startedAt, prepared.timeoutMs, kind),
1287
+ );
1167
1288
  let onCancel: (() => void) | undefined;
1168
1289
  if (parentSignal) {
1169
- onCancel = () => { void cancelAgent(handle.name, herdrCli.exec); };
1290
+ onCancel = () => {
1291
+ void (kind === "herdr-app"
1292
+ ? cancelAppAgent(paneRef, herdrAppCli.exec)
1293
+ : cancelAgent(paneRef, herdrCli.exec));
1294
+ };
1170
1295
  // An already-aborted signal never fires its listeners — cancel now.
1171
1296
  if (parentSignal.aborted) onCancel();
1172
1297
  else parentSignal.addEventListener("abort", onCancel, { once: true });
1173
1298
  }
1174
1299
  try {
1300
+ if (app) {
1301
+ return await executeHerdrAppTask(handle, {
1302
+ onState: onActivity ? progress : undefined,
1303
+ advisorWaitMs: subSettings.advisorWaitSecs * 1000,
1304
+ onAdvisorPhase: onActivity ? progress : undefined,
1305
+ signal: parentSignal,
1306
+ });
1307
+ }
1175
1308
  return await executeHerdrTask(handle, {
1176
- onState: onActivity
1177
- ? (state) => onActivity(herdrProgress(handle.agentType, task, state, startedAt, prepared.timeoutMs))
1178
- : undefined,
1309
+ onState: onActivity ? progress : undefined,
1179
1310
  // The child's own advisor reviews the settled turn and may steer a
1180
1311
  // correction into it — wait for that verdict before collecting, so
1181
1312
  // the parent never consumes a draft the child is about to fix.
1182
1313
  advisorWaitMs: subSettings.advisorWaitSecs * 1000,
1183
- onAdvisorPhase: onActivity
1184
- ? (phase) => onActivity(herdrProgress(handle.agentType, task, phase, startedAt, prepared.timeoutMs))
1185
- : undefined,
1314
+ onAdvisorPhase: onActivity ? progress : undefined,
1186
1315
  signal: parentSignal,
1187
1316
  });
1188
1317
  } catch (err) {
1189
- return makeErrorResult(agentName, task, `herdr delegation failed: ${err instanceof Error ? err.message : String(err)}`);
1318
+ return makeErrorResult(agentName, task, `${kind} delegation failed: ${err instanceof Error ? err.message : String(err)}`);
1190
1319
  } finally {
1191
1320
  // Settled: stop the keep-alive and detach the abort listener so a
1192
1321
  // later abort never keystrokes a completed step's pane.
@@ -1343,7 +1472,8 @@ ${lines.join("\n")}`;
1343
1472
  const historyId = makeForegroundHistoryId(thread.createdAt);
1344
1473
  recordForegroundStart(historyId, step.agent, dispatchTask, thread.createdAt);
1345
1474
  const result = herdrActive
1346
- ? await startHerdrOne(
1475
+ ? await startPaneOne(
1476
+ runnerKind as "herdr" | "herdr-app",
1347
1477
  step.agent, dispatchTask, step.cwd,
1348
1478
  signal, step.timeout ?? params.timeout,
1349
1479
  (progress) => threadStore.updateProgress(thread.id, progress),
@@ -1424,16 +1554,14 @@ ${lines.join("\n")}`;
1424
1554
  }
1425
1555
 
1426
1556
  const last = results[results.length - 1];
1427
- // Chain deliverable: final output plus every step's worktree patch,
1428
- // labeled so the parent can merge them in order.
1429
- const chainPatches = results
1430
- .map((r, i) => (formatPatchBlock(r) ? `Step ${i + 1} (${r.agent}): ${formatPatchBlock(r)}` : ""))
1431
- .filter(Boolean)
1432
- .join("\n\n");
1557
+ // Chain deliverable: the FINAL step's output first (what callers act
1558
+ // on), then every step's report so intermediate work is not lost —
1559
+ // `{previous}` only ever carries one step forward, so without this the
1560
+ // earlier findings vanish from the result. Patches stay labeled per
1561
+ // step so the parent can merge them in order.
1562
+ const finalText = getFinalOutput(last.messages) || "(no output)";
1433
1563
  return {
1434
- content: [
1435
- { type: "text", text: [getFinalOutput(last.messages) || "(no output)", chainPatches].filter(Boolean).join("\n\n") },
1436
- ],
1564
+ content: [{ type: "text", text: formatChainReport(finalText, results) }],
1437
1565
  details: makeDetails("chain")(results),
1438
1566
  };
1439
1567
  }
@@ -1491,17 +1619,27 @@ ${lines.join("\n")}`;
1491
1619
  // Herdr: materialise every pane up front so all delegated agents are
1492
1620
  // visible in herdr before any work starts, then submit prompts under
1493
1621
  // the concurrency limit below.
1622
+ const appPanes = runnerKind === "herdr-app";
1623
+ // Both backends: a handle identifies its pane by `address` (app) or
1624
+ // `name` (TUI) — one resolver keeps the cancel wiring honest.
1625
+ const paneRef = (h: HerdrHandle | HerdrAppHandle) => ("address" in h ? h.address : h.name);
1626
+ const cancelPane = (h: HerdrHandle | HerdrAppHandle) => {
1627
+ if (appPanes) void cancelAppAgent(paneRef(h), herdrAppCli.exec);
1628
+ else void cancelAgent(paneRef(h), herdrCli.exec);
1629
+ };
1494
1630
  const herdrPrepared = herdrActive
1495
1631
  ? await Promise.all(params.tasks.map(async (t) => {
1496
1632
  const startedAt = Date.now();
1497
- const prepared = await prepareHerdrOne(t.agent, t.task, t.cwd, t.timeout ?? params.timeout, t.solutionSpace);
1633
+ const prepared = appPanes
1634
+ ? await prepareHerdrAppOne(t.agent, t.task, t.cwd, t.timeout ?? params.timeout, t.solutionSpace)
1635
+ : await prepareHerdrOne(t.agent, t.task, t.cwd, t.timeout ?? params.timeout, t.solutionSpace);
1498
1636
  if ("error" in prepared) return { ok: false as const, error: prepared.error, startedAt };
1499
1637
  return { ok: true as const, handle: prepared.handle, timeoutMs: prepared.timeoutMs, startedAt: prepared.startedAt };
1500
1638
  }))
1501
1639
  : undefined;
1502
1640
  if (herdrPrepared) {
1503
1641
  const cancelAll = () => {
1504
- for (const p of herdrPrepared) if (p.ok) void cancelAgent(p.handle.name, herdrCli.exec);
1642
+ for (const p of herdrPrepared) if (p.ok) cancelPane(p.handle);
1505
1643
  };
1506
1644
  if (signal) {
1507
1645
  if (signal.aborted) cancelAll();
@@ -1550,7 +1688,7 @@ ${lines.join("\n")}`;
1550
1688
  // Skip if already aborted by sibling failure or parent abort
1551
1689
  if (parallelController.signal.aborted) {
1552
1690
  const preparedSkip = herdrPrepared?.[index];
1553
- if (preparedSkip?.ok) void cancelAgent(preparedSkip.handle.name, herdrCli.exec);
1691
+ if (preparedSkip?.ok) cancelPane(preparedSkip.handle);
1554
1692
  // Sibling/parent cancellation surfaces as "aborted", not "error" —
1555
1693
  // render and /subagent history key off the stopReason.
1556
1694
  const skipReason =
@@ -1570,7 +1708,16 @@ ${lines.join("\n")}`;
1570
1708
  const prepared = herdrPrepared?.[index];
1571
1709
  const result = prepared
1572
1710
  ? prepared.ok
1573
- ? await executeHerdrTask(prepared.handle, {
1711
+ ? await (appPanes
1712
+ ? executeHerdrAppTask(prepared.handle as HerdrAppHandle, {
1713
+ onState: (state) => threadStore.updateProgress(
1714
+ parallelThreads[index].id,
1715
+ herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs, "herdr-app"),
1716
+ ),
1717
+ advisorWaitMs: subSettings.advisorWaitSecs * 1000,
1718
+ signal: parallelController.signal,
1719
+ })
1720
+ : executeHerdrTask(prepared.handle as HerdrHandle, {
1574
1721
  onState: (state) => threadStore.updateProgress(
1575
1722
  parallelThreads[index].id,
1576
1723
  herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs),
@@ -1578,7 +1725,7 @@ ${lines.join("\n")}`;
1578
1725
  // Covers abortOnFailure AND parent abort (parent abort
1579
1726
  // feeds parallelController via onParentAbort).
1580
1727
  signal: parallelController.signal,
1581
- })
1728
+ }))
1582
1729
  : makeErrorResult(t.agent, t.task, prepared.error)
1583
1730
  : await runOne(
1584
1731
  t.agent, t.task, t.cwd,
@@ -1671,7 +1818,11 @@ ${lines.join("\n")}`;
1671
1818
  if (ctx.mode === "tui") widget.ensureWidget(ctx);
1672
1819
  // A foreground rerun of a pinned-sdk / disabled / unprobed call would
1673
1820
  // also run in-process — only advise when it would really delegate.
1674
- const hint = backgroundHerdrHint(await wouldHerdrDelegate(params.runner, (ctx as any).settings?.subagent, herdrCli.exec));
1821
+ const hint = backgroundHerdrHint(
1822
+ await wouldHerdrDelegate(params.runner, (ctx as any).settings?.subagent, herdrCli.exec) ||
1823
+ (params.runner === undefined && herdrAppEnvDetected() && !herdrAppDisabled((ctx as any).settings?.subagent)
1824
+ && await probeHerdrAppBinary(herdrAppCli.exec)),
1825
+ );
1675
1826
  const autoNote = autoBackground
1676
1827
  ? "Dispatch: the task classifier chose background (long/self-contained) — pass runner or background explicitly to override."
1677
1828
  : "";
@@ -1692,7 +1843,8 @@ ${lines.join("\n")}`;
1692
1843
  const historyId = makeForegroundHistoryId(thread.createdAt);
1693
1844
  recordForegroundStart(historyId, params.agent, params.task, thread.createdAt);
1694
1845
  const result = herdrActive
1695
- ? await startHerdrOne(
1846
+ ? await startPaneOne(
1847
+ runnerKind as "herdr" | "herdr-app",
1696
1848
  params.agent, params.task, params.cwd,
1697
1849
  signal, params.timeout,
1698
1850
  (progress) => threadStore.updateProgress(thread.id, progress),
@@ -1777,6 +1929,7 @@ ${lines.join("\n")}`;
1777
1929
  const scope: AgentScope = args.agentScope ?? "user";
1778
1930
  const fg = theme.fg.bind(theme);
1779
1931
  const now = Date.now();
1932
+ const expandKey = expandKeyLabel(context);
1780
1933
 
1781
1934
  // Live-render driver: while the tool executes, re-render every second
1782
1935
  // (bash.js pattern) so elapsed + tool-call count stay fresh in the TUI.
@@ -1840,7 +1993,7 @@ ${lines.join("\n")}`;
1840
1993
  live;
1841
1994
  }
1842
1995
  if (args.chain.length > cap)
1843
- text += `\n ${fg("muted", `... +${args.chain.length - cap} more${context.expanded ? "" : " (Ctrl+O to expand)"}`)}`;
1996
+ text += `\n ${fg("muted", `... +${args.chain.length - cap} more${context.expanded ? "" : ` (${expandKey} to expand)`}`)}`;
1844
1997
  return new Text(text, 0, 0);
1845
1998
  }
1846
1999
 
@@ -1859,7 +2012,7 @@ ${lines.join("\n")}`;
1859
2012
  text += `\n ${fg(resolveAgentColor(t.agent), t.agent)}${fg("dim", ` ${preview}`)}${live}`;
1860
2013
  }
1861
2014
  if (args.tasks.length > cap)
1862
- text += `\n ${fg("muted", `... +${args.tasks.length - cap} more${context.expanded ? "" : " (Ctrl+O to expand)"}`)}`;
2015
+ text += `\n ${fg("muted", `... +${args.tasks.length - cap} more${context.expanded ? "" : ` (${expandKey} to expand)`}`)}`;
1863
2016
  return new Text(text, 0, 0);
1864
2017
  }
1865
2018
 
@@ -1898,11 +2051,13 @@ ${lines.join("\n")}`;
1898
2051
 
1899
2052
  const fg = theme.fg.bind(theme);
1900
2053
  const mdTheme = getMarkdownTheme();
2054
+ // Host-configured expand key (pi 1.5.x KeybindingHints); literal on older pi.
2055
+ const expandKey = expandKeyLabel(_context);
1901
2056
 
1902
2057
  // --- Single ---
1903
2058
  if (details.mode === "single" && details.results.length === 1) {
1904
2059
  const r = details.results[0];
1905
- return renderSingleResult(r, expanded, theme, resolveAgentColor(r.agent));
2060
+ return renderSingleResult(r, expanded, theme, resolveAgentColor(r.agent), expandKey);
1906
2061
  }
1907
2062
 
1908
2063
  // --- Chain ---
@@ -1932,7 +2087,8 @@ ${lines.join("\n")}`;
1932
2087
  new Text(
1933
2088
  fg("muted", `─── Step ${r.exitCode !== -1 ? "" : "?"}: `) +
1934
2089
  fg(resolveAgentColor(r.agent), r.agent) +
1935
- ` ${stepIcon}`,
2090
+ ` ${stepIcon}` +
2091
+ (r.bestEffort ? ` ${fg("warning", "⚠ best-effort pane capture")}` : ""),
1936
2092
  0,
1937
2093
  0,
1938
2094
  ),
@@ -1971,7 +2127,7 @@ ${lines.join("\n")}`;
1971
2127
  }
1972
2128
  const totalUsage = formatUsageStats(aggregateUsage(details.results));
1973
2129
  if (totalUsage) text += `\n${fg("dim", totalUsage)}`;
1974
- text += `\n${fg("muted", "(Ctrl+O to expand)")}`;
2130
+ text += `\n${fg("muted", `(${expandKey} to expand)`)}`;
1975
2131
  return new Text(text, 0, 0);
1976
2132
  }
1977
2133
 
@@ -2056,7 +2212,7 @@ ${lines.join("\n")}`;
2056
2212
  const totalUsage = formatUsageStats(aggregateUsage(details.results));
2057
2213
  if (totalUsage) text += `\n${fg("dim", totalUsage)}`;
2058
2214
  }
2059
- if (!expanded) text += `\n${fg("muted", "(Ctrl+O to expand)")}`;
2215
+ if (!expanded) text += `\n${fg("muted", `(${expandKey} to expand)`)}`;
2060
2216
  return new Text(text, 0, 0);
2061
2217
  }
2062
2218
 
@@ -2069,6 +2225,111 @@ ${lines.join("\n")}`;
2069
2225
  // herdr control tool — main-session oversight of delegated pane agents
2070
2226
  // ---------------------------------------------------------------------------
2071
2227
 
2228
+ /**
2229
+ * herdr-app flavor of the control tool. Same action surface, different
2230
+ * plumbing: `herdr-app do` for layout (focus/close-tab) and `hc` for the
2231
+ * terminal itself (status/read/prompt/cancel). Handles identify their pane
2232
+ * by hc ADDRESS ("t7"); `name` (the allocated label) is accepted too.
2233
+ */
2234
+ async function runAppControl(
2235
+ action: string,
2236
+ name: string,
2237
+ params: { text?: string; lines?: number; wait?: boolean; timeout?: number },
2238
+ toolResult: (text: string, isError?: boolean) => { content: { type: "text"; text: string }[]; isError: boolean; details: Record<string, unknown> },
2239
+ ) {
2240
+ const entry = findHerdrAppAgent(name);
2241
+ const address = entry?.address ?? name;
2242
+ const delegated = Boolean(entry);
2243
+ const refuseUndelegated = (verb: string) =>
2244
+ 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);
2245
+ switch (action) {
2246
+ case "list": {
2247
+ const entries = getHerdrAppRegistry();
2248
+ if (entries.length === 0) {
2249
+ 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).");
2250
+ }
2251
+ const lines: string[] = [];
2252
+ for (const e of entries) {
2253
+ const info = await getAppTerminal(e.address, herdrAppCli.exec);
2254
+ lines.push(`- ${e.name} · ${e.agentType} · ${info?.status ?? "unknown"} · tab ${e.tabName} / ${e.address} — ${e.task.slice(0, 60)}${e.task.length > 60 ? "…" : ""}`);
2255
+ }
2256
+ return toolResult(`Delegated herdr-app agents (${entries.length}):\n${lines.join("\n")}`);
2257
+ }
2258
+ case "status": {
2259
+ const info = await getAppTerminal(address, herdrAppCli.exec);
2260
+ if (!info) return toolResult(`No herdr-app terminal "${name}".`, true);
2261
+ return toolResult(`${name}: ${info.status} (${info.state}; tab ${entry?.tabName ?? "?"}${entry ? ` / ${info.address}` : ""}${info.cwd ? `, cwd ${info.cwd}` : ""})`);
2262
+ }
2263
+ case "read": {
2264
+ const res = await readAppTerminal(address, params.lines ?? 120, herdrAppCli.exec);
2265
+ if (!res.ok) return toolResult(`hc read failed: ${res.text}`, true);
2266
+ return toolResult(
2267
+ res.text.trim() || (entry?.readOnly
2268
+ ? "(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)"
2269
+ : "(no readable output — the agent may be rendering on the alternate screen; prompt it to write its report to a file)"),
2270
+ );
2271
+ }
2272
+ case "prompt": {
2273
+ if (!params.text) return toolResult('Missing text for action "prompt".', true);
2274
+ if (Buffer.byteLength(params.text, "utf8") > HERDR_TASK_BUDGET) {
2275
+ return toolResult(`Prompt exceeds the ${HERDR_TASK_BUDGET}-byte budget (delivery wrapper included) — shorten it.`, true);
2276
+ }
2277
+ if (!delegated) return refuseUndelegated("prompt");
2278
+ const text = wrapAppTaskPrompt(params.text, entry!.resultFile, entry!.readOnly);
2279
+ if (!params.wait) {
2280
+ const sent = await sendAppPrompt(address, text, herdrAppCli.exec);
2281
+ return toolResult(sent.ok ? `Prompt submitted to ${name}.` : `hc send failed: ${sent.error}`, !sent.ok);
2282
+ }
2283
+ const timeoutMs = Math.min(params.timeout ?? 120_000, MAX_TIMEOUT_MS);
2284
+ const stampBefore = await fs.stat(entry!.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
2285
+ const outcome = await promptAppAndWait({ address, text, timeoutMs, exec: herdrAppCli.exec });
2286
+ if (outcome.error) return toolResult(`${name}: ${outcome.error} (state: ${outcome.state})`, true);
2287
+ const collected = await collectAppResult({ handle: entry!, exec: herdrAppCli.exec });
2288
+ if (collected.source === "file") {
2289
+ const stampAfter = await fs.stat(entry!.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
2290
+ if (stampAfter === stampBefore) {
2291
+ return toolResult(`${name}: ${outcome.state} (no new report file content for this follow-up)`);
2292
+ }
2293
+ }
2294
+ return toolResult(`${name}: ${outcome.state}${collected.output ? `\n\n${collected.output}` : ""}`);
2295
+ }
2296
+ case "cancel": {
2297
+ if (!delegated) return refuseUndelegated("cancel");
2298
+ await cancelAppAgent(address, herdrAppCli.exec);
2299
+ return toolResult(`Interrupted ${name} (hc interrupt, plus hc kill if it was still working).`);
2300
+ }
2301
+ case "focus": {
2302
+ const tabId = entry?.tabId;
2303
+ if (!tabId) return toolResult(`No delegated herdr-app agent named "${name}" (focus needs a tab this session knows).`, true);
2304
+ const res = await focusAppTab(tabId, herdrAppCli.exec);
2305
+ return toolResult(res.ok ? `Focused tab ${entry!.tabName} (${tabId}).` : `herdr-app tab.select failed: ${res.error}`, !res.ok);
2306
+ }
2307
+ case "close-tab": {
2308
+ if (!delegated) return toolResult(`"${name}" was not delegated by this session — refusing to close tabs this session did not create.`, true);
2309
+ if (!entry!.tabCreatedHere) {
2310
+ 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);
2311
+ }
2312
+ const { siblings: busy, self: selfBusy } = await appTabCloseBlockers(entry!, herdrAppCli.exec);
2313
+ if (busy.length > 0) {
2314
+ 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);
2315
+ }
2316
+ if (selfBusy) {
2317
+ return toolResult(`"${name}" is still ${selfBusy} — cancel it first (action "cancel") or wait for it to settle before closing its tab.`, true);
2318
+ }
2319
+ const res = await closeAppTab(entry!.tabId, herdrAppCli.exec);
2320
+ if (!res.ok) return toolResult(`herdr-app tab.close failed: ${res.error}`, true);
2321
+ forgetHerdrAppTab(entry!.tabName);
2322
+ return toolResult(`Closed tab ${entry!.tabName} (all its panes).`);
2323
+ }
2324
+ case "forget": {
2325
+ if (!delegated) return toolResult(`"${name}" was not delegated by this session — nothing to forget.`, true);
2326
+ forgetHerdrAppTab(entry!.tabName);
2327
+ return toolResult(`Forgot ${name} (registry entry only — app tabs/terminals untouched).`);
2328
+ }
2329
+ }
2330
+ return toolResult(`Unknown action "${action}".`, true);
2331
+ }
2332
+
2072
2333
  const HerdrControlParams = Type.Object({
2073
2334
  action: StringEnum(["list", "status", "read", "prompt", "cancel", "focus", "close-tab", "forget"] as const, {
2074
2335
  description:
@@ -2089,7 +2350,7 @@ ${lines.join("\n")}`;
2089
2350
  name: "herdr",
2090
2351
  label: "Herdr",
2091
2352
  description: [
2092
- "Control agents this session delegated to herdr panes (subagent runner:\"herdr\", automatic inside herdr).",
2353
+ "Control agents this session delegated to visible herdr panes — herdr TUI (HERDR_ENV) or herdr-app (HC_TERMINAL_ID; subagent delegation is automatic in both).",
2093
2354
  "Actions: list, status, read, prompt, cancel, focus, close-tab, forget.",
2094
2355
  ].join(" "),
2095
2356
  parameters: HerdrControlParams,
@@ -2106,8 +2367,10 @@ ${lines.join("\n")}`;
2106
2367
  isError,
2107
2368
  details: {},
2108
2369
  });
2109
- if (!herdrEnvDetected()) {
2110
- return toolResult("Not running inside herdr (HERDR_ENV!=1). Start pi inside a herdr pane to delegate agents to herdr tabs.", true);
2370
+ const tuiMode = herdrTuiEnvDetected();
2371
+ const appMode = !tuiMode && herdrAppEnvDetected();
2372
+ if (!tuiMode && !appMode) {
2373
+ return toolResult("Not running inside herdr: no HERDR_ENV (herdr TUI) and no HC_TERMINAL_ID (herdr-app). Start pi inside a herdr pane or a Herdr app terminal to delegate agents to visible panes.", true);
2111
2374
  }
2112
2375
  if (herdrDisabled(undefined)) {
2113
2376
  // Delegated child session (PI_SUBAGENT_HERDR=off): no herdr control.
@@ -2117,6 +2380,7 @@ ${lines.join("\n")}`;
2117
2380
  return toolResult(`Missing name for action "${params.action}". Use a herdr agent name from action "list" (e.g. scout-1).`, true);
2118
2381
  }
2119
2382
  const name = params.name!;
2383
+ if (appMode) return runAppControl(params.action, name, params, toolResult);
2120
2384
  // Mutating actions are scoped to agents this session delegated —
2121
2385
  // the model must not drive (or kill) panes it never spawned.
2122
2386
  if ((params.action === "prompt" || params.action === "cancel") && !isDelegatedHerdrAgent(name)) {