ceulen 0.27.0 → 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 CHANGED
@@ -1,5 +1,65 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.28.0 — 2026-11-18
4
+
5
+ **Rex is now a first-class subagent delegation backend.** ceulen's visible-pane
6
+ delegation knew the herdr TUI (`HERDR_ENV`) and the Herdr desktop app
7
+ (`HC_TERMINAL_ID`, herdr-app + `hc`) — inside **Rex** (the `rex` CLI + server,
8
+ `REX_SESSION`) every dispatch silently fell back to the in-process SDK runner
9
+ and the `herdr` control tool refused to run at all. New
10
+ `subagent/lib/rex.ts` plus a runner/control-tool rewire fixes that: one WINDOW
11
+ per agent type (`rex window new`, adopted when already labelled), one PANE per
12
+ instance (`rex split` beside the window's last tiled block), the child pi
13
+ started by the block's command with the same persona/model/thinking/tools
14
+ contract, and reports through the same file/inline delivery contract.
15
+
16
+ - **Auto-detection, no new settings.** `REX_SESSION` plus a `rex` binary that
17
+ answers `rex version` (Rex has no `--version`) selects the backend.
18
+ Resolution order is herdr TUI → rex → herdr-app → sdk, and an explicit
19
+ `runner:"herdr"` still keeps its "not running inside herdr" error instead of
20
+ silently re-routing. `subagent.herdr:"off"` and the `PI_SUBAGENT_HERDR=off`
21
+ child guard disable delegation on all three backends.
22
+ - **No turn-following primitive, so the turn proof is a timestamp.** `rex wait`
23
+ waits for a block to EXIT, which is useless for a long-lived pi, so
24
+ `promptRexAndWait` is built from `program_status` polling (OSC 7501, which pi
25
+ publishes): readiness gate → `block send` + `block send-key enter` → poll.
26
+ With no turn counter, a settle is accepted only when the ROOT status record's
27
+ `updated_at` moved past the pre-paste baseline (or the child was seen
28
+ working), so a paste that never submitted reports "pasted but never
29
+ submitted" instead of being collected as a success.
30
+ - **`format` answers a head slice.** Any reply carrying a blob `id` is re-read
31
+ from `total - N` via `blob_read`; asking for the whole scrollback would park
32
+ megabytes in the parent's context, and trusting the head silently returned
33
+ boot chrome instead of the child's reply (found live while gating this
34
+ release).
35
+ - **Rex children DO get environment variables** by way of a `/usr/bin/env`
36
+ command wrapper — unlike herdr-app — so they carry the advisor review marker
37
+ (the parent waits for the child's own advisor before collecting) *and* the
38
+ `PI_SUBAGENT_HERDR=off` recursion guard plus `CEULEN_THINK_GATE_OFF=1`.
39
+ - **Echo is never a report.** A pane capture is cut to the text after the
40
+ delivery contract (falling back to the task echo), and an echo-only pane
41
+ yields no output, so the dispatch fails loudly.
42
+ - **Full control surface, scoped.** The `herdr` tool gained a rex branch for
43
+ list/status/read/prompt/cancel/focus/close-tab/forget. Mutating actions only
44
+ touch agents this session delegated, `close-tab` closes the rex WINDOW and
45
+ refuses while a sibling is busy or its state is unverifiable, and adopted
46
+ windows (label match) are never close-eligible. `RunnerKind`,
47
+ `SubagentDetails.runner` and the widget's pane-label gate all carry `rex`.
48
+ - **CLI quirks encoded, each with a regression test:** `rex block call` takes
49
+ SHORT method names (the fully-qualified name is rejected), and
50
+ `rex session inspect` takes the session POSITIONALLY and rejects the global
51
+ `-s` prefix (the prefixed form made every window adoption fail with "window
52
+ has no block to split beside").
53
+
54
+ Verified: `tsc --noEmit` clean; full `npm test` **3019 pass / 0 fail / 3
55
+ env-gated skips** (32 of them in the new `test/rex.test.ts`); `npm pack
56
+ --dry-run` ships `lib/rex.ts` + its suite. Live-verified against a running Rex
57
+ server: single dispatch, window adoption, write-capable report-file agents,
58
+ parallel (multi-agent-type) and chain (`{previous}`) modes, read-only inline
59
+ collection, the full `herdr` control surface (including the busy-sibling
60
+ refusal and stale-entry `forget`), `runner:"sdk"` pinning, and
61
+ `background:true` correctly staying in-process with an honest receipt.
62
+
3
63
  ## 0.27.0 — 2026-11-17
4
64
 
5
65
  **herdr-app is now a first-class subagent delegation backend.** ceulen's
@@ -152,7 +152,7 @@ export const MODULES: ModuleEntry[] = [
152
152
  // Subagent after ponytail: ponytail's tool_call hook injects into the
153
153
  // `subagent` tool's instructions param — hooks resolve at call time, so
154
154
  // order is not load-bearing; this is grouping readability.
155
- { name: "subagent", category: "Tasks", describe: "In-process subagents: scout/tester/worker/planner/reviewer agents, role-based model pools, classifier tier+thinking routing, background tasks with liveness, herdr delegation.", load: subagentModule, config: subagentConfig },
155
+ { name: "subagent", category: "Tasks", describe: "In-process subagents: scout/tester/worker/planner/reviewer agents, role-based model pools, classifier tier+thinking routing, background tasks with liveness, herdr/rex pane delegation.", load: subagentModule, config: subagentConfig },
156
156
  // Plan after subagent: its tool gating reads subagent agent frontmatter
157
157
  // (sandbox: read-only) and its before_agent_start must compose BEFORE
158
158
  // steering (the last prompt rewriter — see its entry below).
@@ -115,6 +115,29 @@ import {
115
115
  forgetHerdrAppTab,
116
116
  type HerdrAppHandle,
117
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";
118
141
  /** Keep-alive cadence for herdr delegations (test seam: shorten to assert). */
119
142
  export const herdrHeartbeat = { intervalMs: 30_000 };
120
143
  import {
@@ -150,7 +173,7 @@ import {
150
173
  // ---------------------------------------------------------------------------
151
174
 
152
175
  /** Visible-pane delegation backend for one dispatch. */
153
- type RunnerKind = "sdk" | "herdr" | "herdr-app";
176
+ type RunnerKind = "sdk" | "herdr" | "herdr-app" | "rex";
154
177
 
155
178
  // ---------------------------------------------------------------------------
156
179
  // Helpers
@@ -240,7 +263,7 @@ const SubagentParams = Type.Object({
240
263
  instructions: Type.Optional(Type.String({ description: "Bounded repository/task instructions passed to each child (max 16 KB)" })),
241
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'." })),
242
265
  runner: Type.Optional(StringEnum(["sdk", "herdr"] as const, {
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.',
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.',
244
267
  })),
245
268
  abortOnFailure: Type.Optional(Type.Boolean({ description: "In parallel mode, cancel remaining tasks when one fails. Default: false.", default: false })),
246
269
  });
@@ -256,8 +279,8 @@ interface SubagentDetails {
256
279
  results: SubAgentResult[];
257
280
  /** Set when a background task was started (single mode + background:true). */
258
281
  backgroundTaskId?: string;
259
- /** Set when the run was delegated to herdr panes. */
260
- runner?: "herdr";
282
+ /** Set when the run was delegated to a visible-pane backend. */
283
+ runner?: "herdr" | "herdr-app" | "rex";
261
284
  }
262
285
 
263
286
  // ---------------------------------------------------------------------------
@@ -672,14 +695,17 @@ ${lines.join("\n")}`;
672
695
  };
673
696
 
674
697
  /**
675
- * Effective runner across BOTH visible-pane backends.
698
+ * Effective runner across ALL THREE visible-pane backends.
676
699
  *
677
700
  * herdr TUI (`HERDR_ENV=1`, `herdr` CLI) keeps its exact existing semantics
678
701
  * (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.
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.
683
709
  */
684
710
  async function resolveRunner(
685
711
  requested: "sdk" | "herdr" | undefined,
@@ -687,6 +713,9 @@ ${lines.join("\n")}`;
687
713
  ): Promise<{ runner: RunnerKind; error?: string }> {
688
714
  const tui = await resolveEffectiveRunner(requested, subagentSettings, herdrCli.exec);
689
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
+ }
690
719
  if (!herdrAppEnvDetected() || herdrAppDisabled(subagentSettings)) return tui;
691
720
  if (!await probeHerdrAppBinary(herdrAppCli.exec)) return tui;
692
721
  return { runner: "herdr-app" };
@@ -712,9 +741,9 @@ ${lines.join("\n")}`;
712
741
  "For background single tasks use background:true — you will be notified on completion; DO NOT poll or sleep.",
713
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.',
714
743
  "Set solutionSpace when a task's openness isn't obvious from its text — it feeds tier/thinking routing.",
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.",
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.",
716
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).",
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.`,
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.`,
718
747
  "Use /subagent list to list all available agents, /subagent <name> for agent details, /subagent @role for role detail.",
719
748
  ],
720
749
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
@@ -771,7 +800,7 @@ ${lines.join("\n")}`;
771
800
  .some((n) => agents.find((a) => a.name === n)?.sandbox === "worktree");
772
801
  if (herdrActive && (requestedMerge || worktreeAgentRequested)) {
773
802
  return {
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" : ""}.` }],
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" : ""}.` }],
775
804
  details: { mode: "single" as const, agentScope, projectAgentsDir: discovery.projectAgentsDir, results: [] },
776
805
  isError: true,
777
806
  };
@@ -784,7 +813,7 @@ ${lines.join("\n")}`;
784
813
  agentScope,
785
814
  projectAgentsDir: discovery.projectAgentsDir,
786
815
  results,
787
- runner: herdrActive ? "herdr" : undefined,
816
+ runner: herdrActive ? runnerKind : undefined,
788
817
  });
789
818
 
790
819
  // Task-control results (operation status/cancel) describe an existing
@@ -1074,7 +1103,7 @@ ${lines.join("\n")}`;
1074
1103
  }
1075
1104
 
1076
1105
  // 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 {
1106
+ function herdrProgress(agentName: string, task: string, state: string, startedAt: number, timeoutMs: number, kind: "herdr" | "herdr-app" | "rex" = "herdr"): SubAgentProgress {
1078
1107
  const now = Date.now();
1079
1108
  return {
1080
1109
  label: `${kind}: ${state}`,
@@ -1249,11 +1278,41 @@ ${lines.join("\n")}`;
1249
1278
  }
1250
1279
  }
1251
1280
 
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.
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.
1255
1314
  async function startPaneOne(
1256
- kind: "herdr" | "herdr-app",
1315
+ kind: "herdr" | "herdr-app" | "rex",
1257
1316
  agentName: string,
1258
1317
  task: string,
1259
1318
  cwd: string | undefined,
@@ -1267,13 +1326,16 @@ ${lines.join("\n")}`;
1267
1326
  verdict?: RoutingVerdict,
1268
1327
  ): Promise<SubAgentResult> {
1269
1328
  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);
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);
1273
1335
  if ("error" in prepared) return makeErrorResult(agentName, task, prepared.error);
1274
1336
  const { startedAt } = prepared;
1275
1337
  // Narrowing the union by `app` keeps every later access type-safe.
1276
- const handle = prepared.handle as HerdrAppHandle & HerdrHandle;
1338
+ const handle = prepared.handle as HerdrAppHandle & HerdrHandle & RexHandle;
1277
1339
  // Keep-alive parity with the SDK path: a long pane run must emit
1278
1340
  // onUpdate traffic or the host may idle-abort the tool call.
1279
1341
  const stopHeartbeat = onUpdate ? startHeartbeat(() => {
@@ -1281,22 +1343,32 @@ ${lines.join("\n")}`;
1281
1343
  onUpdate({ content: [{ type: "text", text: "" }], details: heartbeatDetails?.() ?? makeDetails("single")([]) });
1282
1344
  widget.requestRender();
1283
1345
  }, herdrHeartbeat.intervalMs) : undefined;
1284
- const paneRef = kind === "herdr-app" ? handle.address : handle.name;
1346
+ const paneRef = kind === "herdr-app" || rex ? handle.address : handle.name;
1285
1347
  const progress = (state: string) => onActivity?.(
1286
1348
  herdrProgress(handle.agentType, task, state, startedAt, prepared.timeoutMs, kind),
1287
1349
  );
1288
1350
  let onCancel: (() => void) | undefined;
1289
1351
  if (parentSignal) {
1290
1352
  onCancel = () => {
1291
- void (kind === "herdr-app"
1292
- ? cancelAppAgent(paneRef, herdrAppCli.exec)
1293
- : cancelAgent(paneRef, herdrCli.exec));
1353
+ void (rex
1354
+ ? cancelRexAgent(paneRef, rexCli.exec)
1355
+ : kind === "herdr-app"
1356
+ ? cancelAppAgent(paneRef, herdrAppCli.exec)
1357
+ : cancelAgent(paneRef, herdrCli.exec));
1294
1358
  };
1295
1359
  // An already-aborted signal never fires its listeners — cancel now.
1296
1360
  if (parentSignal.aborted) onCancel();
1297
1361
  else parentSignal.addEventListener("abort", onCancel, { once: true });
1298
1362
  }
1299
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
+ }
1300
1372
  if (app) {
1301
1373
  return await executeHerdrAppTask(handle, {
1302
1374
  onState: onActivity ? progress : undefined,
@@ -1473,7 +1545,7 @@ ${lines.join("\n")}`;
1473
1545
  recordForegroundStart(historyId, step.agent, dispatchTask, thread.createdAt);
1474
1546
  const result = herdrActive
1475
1547
  ? await startPaneOne(
1476
- runnerKind as "herdr" | "herdr-app",
1548
+ runnerKind as "herdr" | "herdr-app" | "rex",
1477
1549
  step.agent, dispatchTask, step.cwd,
1478
1550
  signal, step.timeout ?? params.timeout,
1479
1551
  (progress) => threadStore.updateProgress(thread.id, progress),
@@ -1620,19 +1692,23 @@ ${lines.join("\n")}`;
1620
1692
  // visible in herdr before any work starts, then submit prompts under
1621
1693
  // the concurrency limit below.
1622
1694
  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);
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);
1628
1702
  else void cancelAgent(paneRef(h), herdrCli.exec);
1629
1703
  };
1630
1704
  const herdrPrepared = herdrActive
1631
1705
  ? await Promise.all(params.tasks.map(async (t) => {
1632
1706
  const startedAt = Date.now();
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);
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);
1636
1712
  if ("error" in prepared) return { ok: false as const, error: prepared.error, startedAt };
1637
1713
  return { ok: true as const, handle: prepared.handle, timeoutMs: prepared.timeoutMs, startedAt: prepared.startedAt };
1638
1714
  }))
@@ -1708,24 +1784,33 @@ ${lines.join("\n")}`;
1708
1784
  const prepared = herdrPrepared?.[index];
1709
1785
  const result = prepared
1710
1786
  ? prepared.ok
1711
- ? await (appPanes
1712
- ? executeHerdrAppTask(prepared.handle as HerdrAppHandle, {
1787
+ ? await (rexPanes
1788
+ ? executeRexTask(prepared.handle as RexHandle, {
1713
1789
  onState: (state) => threadStore.updateProgress(
1714
1790
  parallelThreads[index].id,
1715
- herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs, "herdr-app"),
1791
+ herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs, "rex"),
1716
1792
  ),
1717
1793
  advisorWaitMs: subSettings.advisorWaitSecs * 1000,
1718
1794
  signal: parallelController.signal,
1719
1795
  })
1720
- : executeHerdrTask(prepared.handle as HerdrHandle, {
1721
- onState: (state) => threadStore.updateProgress(
1722
- parallelThreads[index].id,
1723
- herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs),
1724
- ),
1725
- // Covers abortOnFailure AND parent abort (parent abort
1726
- // feeds parallelController via onParentAbort).
1727
- signal: parallelController.signal,
1728
- }))
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
+ }))
1729
1814
  : makeErrorResult(t.agent, t.task, prepared.error)
1730
1815
  : await runOne(
1731
1816
  t.agent, t.task, t.cwd,
@@ -1821,7 +1906,9 @@ ${lines.join("\n")}`;
1821
1906
  const hint = backgroundHerdrHint(
1822
1907
  await wouldHerdrDelegate(params.runner, (ctx as any).settings?.subagent, herdrCli.exec) ||
1823
1908
  (params.runner === undefined && herdrAppEnvDetected() && !herdrAppDisabled((ctx as any).settings?.subagent)
1824
- && await probeHerdrAppBinary(herdrAppCli.exec)),
1909
+ && await probeHerdrAppBinary(herdrAppCli.exec)) ||
1910
+ (params.runner === undefined && rexEnvDetected() && !rexDisabled((ctx as any).settings?.subagent)
1911
+ && await probeRexBinary(rexCli.exec)),
1825
1912
  );
1826
1913
  const autoNote = autoBackground
1827
1914
  ? "Dispatch: the task classifier chose background (long/self-contained) — pass runner or background explicitly to override."
@@ -1844,7 +1931,7 @@ ${lines.join("\n")}`;
1844
1931
  recordForegroundStart(historyId, params.agent, params.task, thread.createdAt);
1845
1932
  const result = herdrActive
1846
1933
  ? await startPaneOne(
1847
- runnerKind as "herdr" | "herdr-app",
1934
+ runnerKind as "herdr" | "herdr-app" | "rex",
1848
1935
  params.agent, params.task, params.cwd,
1849
1936
  signal, params.timeout,
1850
1937
  (progress) => threadStore.updateProgress(thread.id, progress),
@@ -2330,6 +2417,110 @@ ${lines.join("\n")}`;
2330
2417
  return toolResult(`Unknown action "${action}".`, true);
2331
2418
  }
2332
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
+
2333
2524
  const HerdrControlParams = Type.Object({
2334
2525
  action: StringEnum(["list", "status", "read", "prompt", "cancel", "focus", "close-tab", "forget"] as const, {
2335
2526
  description:
@@ -2350,15 +2541,15 @@ ${lines.join("\n")}`;
2350
2541
  name: "herdr",
2351
2542
  label: "Herdr",
2352
2543
  description: [
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).",
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).",
2354
2545
  "Actions: list, status, read, prompt, cancel, focus, close-tab, forget.",
2355
2546
  ].join(" "),
2356
2547
  parameters: HerdrControlParams,
2357
- promptSnippet: "Control delegated herdr pane agents (list/status/read/prompt/cancel/focus/close-tab/forget)",
2548
+ promptSnippet: "Control delegated pane agents — herdr/rex (list/status/read/prompt/cancel/focus/close-tab/forget)",
2358
2549
  promptGuidelines: [
2359
- "Use for oversight of herdr-delegated subagents: status/read to inspect, prompt to continue an agent's session, cancel to interrupt, focus to raise its tab, forget to drop a stale registry entry.",
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.",
2360
2551
  "A blocked agent waits for human input — answer it in the pane directly, or cancel and re-delegate.",
2361
- "prompt/cancel/forget only accept agents this session delegated and close-tab only tabs it created; status/read/focus can inspect any live herdr agent.",
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.",
2362
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).",
2363
2554
  ],
2364
2555
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
@@ -2369,18 +2560,20 @@ ${lines.join("\n")}`;
2369
2560
  });
2370
2561
  const tuiMode = herdrTuiEnvDetected();
2371
2562
  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);
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);
2374
2566
  }
2375
2567
  if (herdrDisabled(undefined)) {
2376
- // Delegated child session (PI_SUBAGENT_HERDR=off): no herdr control.
2377
- return toolResult("herdr control is disabled in this session (PI_SUBAGENT_HERDR=off child guard).", true);
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);
2378
2570
  }
2379
2571
  if (params.action !== "list" && !params.name) {
2380
- return toolResult(`Missing name for action "${params.action}". Use a herdr agent name from action "list" (e.g. scout-1).`, true);
2572
+ return toolResult(`Missing name for action "${params.action}". Use an agent name from action "list" (e.g. scout-1).`, true);
2381
2573
  }
2382
2574
  const name = params.name!;
2383
2575
  if (appMode) return runAppControl(params.action, name, params, toolResult);
2576
+ if (rexMode) return runRexControl(params.action, name, params, toolResult);
2384
2577
  // Mutating actions are scoped to agents this session delegated —
2385
2578
  // the model must not drive (or kill) panes it never spawned.
2386
2579
  if ((params.action === "prompt" || params.action === "cancel") && !isDelegatedHerdrAgent(name)) {