ceulen 0.27.0 → 0.28.1
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 +100 -0
- package/extensions/lib/registry.test.ts +19 -0
- package/extensions/lib/registry.ts +12 -5
- package/extensions/modules/serena/lib/guidance.ts +7 -6
- package/extensions/modules/serena/test/index.test.ts +3 -0
- package/extensions/modules/serena/worker.ts +69 -7
- package/extensions/modules/subagent/index.ts +251 -58
- package/extensions/modules/subagent/lib/rex.ts +902 -0
- package/extensions/modules/subagent/lib/widget.ts +8 -6
- package/extensions/modules/subagent/test/rex.test.ts +724 -0
- package/package.json +1 -1
|
@@ -0,0 +1,902 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rex delegation backend for the subagent module.
|
|
3
|
+
*
|
|
4
|
+
* Rex (https://rex.superlogical.com, the `rex` CLI + server) is a terminal
|
|
5
|
+
* multiplexer. Pi running inside a Rex-managed terminal has REX_SESSION /
|
|
6
|
+
* REX_BLOCK and a `rex` binary that talks to the local server, so subagent
|
|
7
|
+
* tasks can be delegated to visible interactive pi panes — the herdr-TUI and
|
|
8
|
+
* herdr-app backends' sibling.
|
|
9
|
+
*
|
|
10
|
+
* Topology mirrors the other two so the model's mental model carries over:
|
|
11
|
+
*
|
|
12
|
+
* - One WINDOW (Rex's tab) per agent type, labelled with the agent name,
|
|
13
|
+
* adopted when it already exists.
|
|
14
|
+
* - One PANE (Rex's block) per agent instance: `rex split` beside the
|
|
15
|
+
* window's last tiled block.
|
|
16
|
+
* - Child = full `pi` started by the block's command, persona as a file
|
|
17
|
+
* (`--append-system-prompt`), plus `--model` / `--thinking` / `--tools`.
|
|
18
|
+
* - Results come back via the same report-file contract (pi renders on the
|
|
19
|
+
* alternate screen; read-only children reply inline).
|
|
20
|
+
*
|
|
21
|
+
* Divergences from the herdr backends, all forced by Rex's API surface (each
|
|
22
|
+
* one live-probed against rex 0.1.0-preview.20, API revision 16):
|
|
23
|
+
*
|
|
24
|
+
* - `rex block call` takes SHORT method names (`format`, not
|
|
25
|
+
* `com.superlogical.terminal.format`).
|
|
26
|
+
* - There is no `--wait` that follows a program's TURN: `rex wait` waits for
|
|
27
|
+
* a block to EXIT. Prompting therefore polls `program_status` (OSC 7501,
|
|
28
|
+
* which pi publishes) — see promptRexAndWait.
|
|
29
|
+
* - No turn counter exists, so "the paste became work" is proven by a FRESH
|
|
30
|
+
* `updated_at` on the root status record (probe-verified: a paste that is
|
|
31
|
+
* never submitted leaves the timestamp untouched; a submitted turn moves
|
|
32
|
+
* idle→working→done and stamps each transition).
|
|
33
|
+
* - Env vars ARE reachable by wrapping the child in `/usr/bin/env VAR=…`
|
|
34
|
+
* (unlike herdr-app), so rex children get the advisor marker AND the
|
|
35
|
+
* delegation recursion guard.
|
|
36
|
+
*
|
|
37
|
+
* All CLI calls go through an injectable `exec` (`rexCli`, the `herdrCli` /
|
|
38
|
+
* `herdrAppCli` precedent) so tests script the CLI.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import * as fs from "node:fs/promises";
|
|
42
|
+
import * as path from "node:path";
|
|
43
|
+
import {
|
|
44
|
+
allocateName,
|
|
45
|
+
awaitAdvisorCycle,
|
|
46
|
+
buildHerdrResult,
|
|
47
|
+
buildPiArgs,
|
|
48
|
+
capPaneCapture,
|
|
49
|
+
dispatchStamp,
|
|
50
|
+
HERDR_OFF_ENV,
|
|
51
|
+
HERDR_TASK_BUDGET,
|
|
52
|
+
readReportFile,
|
|
53
|
+
type HerdrAgentState,
|
|
54
|
+
type HerdrExec,
|
|
55
|
+
type PromptOutcome,
|
|
56
|
+
} from "./herdr.ts";
|
|
57
|
+
import { defaultExec, type SubAgentResult } from "./runner.ts";
|
|
58
|
+
import { ADVISOR_MARKER_ENV } from "../../../lib/advisor-marker.js";
|
|
59
|
+
|
|
60
|
+
/** The exec used by the rex backend and control tool. Tests swap this. */
|
|
61
|
+
export const rexCli: { exec: HerdrExec } = { exec: defaultExec };
|
|
62
|
+
|
|
63
|
+
const REX_BIN = "rex";
|
|
64
|
+
/** Timing knobs (test seam: shorten so the failure paths run fast, the
|
|
65
|
+
* herdrHeartbeat precedent). Defaults are the shipped values:
|
|
66
|
+
* - readyTimeoutMs: readiness budget for a fresh child (cold model load +
|
|
67
|
+
* extension startup). Rex has no readiness signal, so this is the ceiling.
|
|
68
|
+
* - pollMs: status poll cadence while waiting for a turn to settle.
|
|
69
|
+
* - unsentGraceMs: how long an unchanged status may sit after the paste
|
|
70
|
+
* before we declare the submit never landed (live-probed: pi's OSC 7501
|
|
71
|
+
* timestamp does not move for a composer paste that was never submitted). */
|
|
72
|
+
export const rexTiming = { readyTimeoutMs: 120_000, pollMs: 700, unsentGraceMs: 8_000 };
|
|
73
|
+
/** Tail window pulled from a pane's scrollback for best-effort collection. */
|
|
74
|
+
const PANE_TAIL_BYTES = 64 * 1024;
|
|
75
|
+
|
|
76
|
+
// ---------------------------------------------------------------------------
|
|
77
|
+
// Detection & kill-switch
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
/** Rex stamps every managed terminal with REX_SESSION; REX_BLOCK alone is not
|
|
81
|
+
* enough (a hand-made `rex` shell has no session unless one is selected). */
|
|
82
|
+
export function rexEnvDetected(): boolean {
|
|
83
|
+
return Boolean(process.env.REX_SESSION);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Same switch as the herdr backends: `subagent.herdr:"off"` and the child
|
|
87
|
+
* recursion guard (`PI_SUBAGENT_HERDR=off`, set on every child we spawn)
|
|
88
|
+
* disable rex delegation. One knob for "visible-pane delegation". */
|
|
89
|
+
export function rexDisabled(subagentSettings?: { herdr?: unknown }): boolean {
|
|
90
|
+
if (subagentSettings?.herdr === "off") return true;
|
|
91
|
+
return process.env[HERDR_OFF_ENV] === "off";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
let binaryProbe: Promise<boolean> | undefined;
|
|
95
|
+
|
|
96
|
+
/** `rex version` answers (Rex has no --version flag). Successes are cached for
|
|
97
|
+
* the process; failures are not (a transient failure must not disable
|
|
98
|
+
* delegation for the whole session — herdr precedent). */
|
|
99
|
+
export async function probeRexBinary(exec: HerdrExec = rexCli.exec): Promise<boolean> {
|
|
100
|
+
const cacheable = exec === defaultExec;
|
|
101
|
+
if (cacheable && binaryProbe) return binaryProbe;
|
|
102
|
+
const res = await exec(REX_BIN, ["version"], { timeout: 5_000 });
|
|
103
|
+
const ok = res.code === 0;
|
|
104
|
+
if (cacheable && ok) binaryProbe = Promise.resolve(true);
|
|
105
|
+
return ok;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Test hook: forget the cached probe result. */
|
|
109
|
+
export function resetRexProbe(): void {
|
|
110
|
+
binaryProbe = undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// Registry — session-scoped, one entry per dispatched pane
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
export interface RexHandle {
|
|
118
|
+
/** Unique allocated name ("scout-1"); also the pane label and pi --name. */
|
|
119
|
+
name: string;
|
|
120
|
+
agentType: string;
|
|
121
|
+
/** Rex WINDOW id (the tab). */
|
|
122
|
+
tabId: string;
|
|
123
|
+
/** Rex BLOCK id — the identity every rex command takes. */
|
|
124
|
+
address: string;
|
|
125
|
+
/** Block id again (buildHerdrResult/pane-ref parity with the other backends). */
|
|
126
|
+
paneId: string;
|
|
127
|
+
resultFile: string;
|
|
128
|
+
advisorMarker: string;
|
|
129
|
+
task: string;
|
|
130
|
+
readOnly?: boolean;
|
|
131
|
+
model: string;
|
|
132
|
+
thinking?: string;
|
|
133
|
+
timeoutMs: number;
|
|
134
|
+
/** False when the window pre-existed (label match) — adopted windows are
|
|
135
|
+
* never eligible for close-window. */
|
|
136
|
+
tabCreatedHere: boolean;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Keyed by the unique agent name; also resolvable by block id. */
|
|
140
|
+
const registry = new Map<string, RexHandle>();
|
|
141
|
+
|
|
142
|
+
export function getRexRegistry(): RexHandle[] {
|
|
143
|
+
return [...registry.values()];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Look up a handle by allocated name OR Rex block id. */
|
|
147
|
+
export function findRexAgent(nameOrBlock: string): RexHandle | undefined {
|
|
148
|
+
const direct = registry.get(nameOrBlock);
|
|
149
|
+
if (direct) return direct;
|
|
150
|
+
for (const entry of registry.values()) {
|
|
151
|
+
if (entry.address === nameOrBlock || entry.paneId === nameOrBlock) return entry;
|
|
152
|
+
}
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function forgetRexWindow(windowId: string): void {
|
|
157
|
+
for (const [key, entry] of registry) {
|
|
158
|
+
if (key === windowId || entry.tabId === windowId) registry.delete(key);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function forgetRexAgent(name: string): void {
|
|
163
|
+
registry.delete(name);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Test hook: reset the session registry. */
|
|
167
|
+
export function clearRexRegistry(): void {
|
|
168
|
+
registry.clear();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
// CLI plumbing
|
|
173
|
+
// ---------------------------------------------------------------------------
|
|
174
|
+
|
|
175
|
+
function firstLine(res: { stdout: string; stderr: string }): string {
|
|
176
|
+
return (res.stderr || res.stdout).trim().split("\n")[0]?.slice(0, 300) ?? "";
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Run a rex command and parse its JSON reply (redirected output is one line).
|
|
180
|
+
* Every call is session-scoped so a block/window id can never cross into
|
|
181
|
+
* another session. */
|
|
182
|
+
async function rexJson(
|
|
183
|
+
exec: HerdrExec,
|
|
184
|
+
args: string[],
|
|
185
|
+
timeoutMs = 20_000,
|
|
186
|
+
): Promise<{ ok: true; data: any } | { ok: false; error: string }> {
|
|
187
|
+
const session = process.env.REX_SESSION;
|
|
188
|
+
const full = session ? ["-s", session, ...args] : args;
|
|
189
|
+
const res = await exec(REX_BIN, full, { timeout: timeoutMs });
|
|
190
|
+
if (res.code !== 0) return { ok: false, error: firstLine(res) ?? `exit ${res.code}` };
|
|
191
|
+
const text = res.stdout.trim();
|
|
192
|
+
if (!text) return { ok: true, data: {} };
|
|
193
|
+
try {
|
|
194
|
+
return { ok: true, data: JSON.parse(text) };
|
|
195
|
+
} catch {
|
|
196
|
+
return { ok: false, error: `rex ${args[0]}: unparseable JSON output` };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** `rex block call -b <block> <method> [json]` → parsed reply. Rex takes the
|
|
201
|
+
* method's SHORT name here (the fully-qualified name is rejected). */
|
|
202
|
+
async function blockCall(
|
|
203
|
+
exec: HerdrExec,
|
|
204
|
+
address: string,
|
|
205
|
+
method: string,
|
|
206
|
+
args?: Record<string, unknown>,
|
|
207
|
+
timeoutMs = 15_000,
|
|
208
|
+
): Promise<{ ok: true; data: any } | { ok: false; error: string }> {
|
|
209
|
+
const argv = ["block", "call", "-b", address, method];
|
|
210
|
+
if (args) argv.push(JSON.stringify(args));
|
|
211
|
+
return rexJson(exec, argv, timeoutMs);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ---------------------------------------------------------------------------
|
|
215
|
+
// Layout: windows (tabs) and blocks (panes)
|
|
216
|
+
// ---------------------------------------------------------------------------
|
|
217
|
+
|
|
218
|
+
export interface RexWindow {
|
|
219
|
+
windowId: string;
|
|
220
|
+
label: string;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export interface RexBlockInfo {
|
|
224
|
+
blockId: string;
|
|
225
|
+
label: string;
|
|
226
|
+
windowId: string;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** `rex window ls --json` → the session's windows (empty on failure). */
|
|
230
|
+
export async function listRexWindows(exec: HerdrExec): Promise<RexWindow[]> {
|
|
231
|
+
const listed = await rexJson(exec, ["window", "ls", "--json"], 20_000);
|
|
232
|
+
if (!listed.ok) return [];
|
|
233
|
+
return (listed.data?.windows ?? [])
|
|
234
|
+
.map((w: any) => ({ windowId: w?.window_id, label: w?.label ?? "" }))
|
|
235
|
+
.filter((w: RexWindow) => typeof w.windowId === "string" && w.windowId.length > 0);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** `rex block ls --json` → the session's blocks (empty on failure). */
|
|
239
|
+
export async function listRexBlocks(exec: HerdrExec): Promise<RexBlockInfo[]> {
|
|
240
|
+
const listed = await rexJson(exec, ["block", "ls", "--json"], 20_000);
|
|
241
|
+
if (!listed.ok) return [];
|
|
242
|
+
return (listed.data?.blocks ?? [])
|
|
243
|
+
.map((b: any) => ({ blockId: b?.block_id, label: b?.label ?? "", windowId: b?.window_id ?? "" }))
|
|
244
|
+
.filter((b: RexBlockInfo) => typeof b.blockId === "string" && b.blockId.length > 0);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** In-order leaf walk of a layout node (`block_id` leaves, `split.before/after`). */
|
|
248
|
+
function layoutBlocks(node: any, out: string[] = []): string[] {
|
|
249
|
+
if (!node || typeof node !== "object") return out;
|
|
250
|
+
if (typeof node.block_id === "string") out.push(node.block_id);
|
|
251
|
+
const split = node.split;
|
|
252
|
+
if (split && typeof split === "object") {
|
|
253
|
+
layoutBlocks(split.before, out);
|
|
254
|
+
layoutBlocks(split.after, out);
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* The block a new split should anchor on: the window's LAST tiled block in
|
|
261
|
+
* layout order (so repeated dispatches fan out instead of crowding the first
|
|
262
|
+
* pane). Falls back to the window's focused block when the layout is missing,
|
|
263
|
+
* and to undefined when the window holds nothing we can prove belongs to it —
|
|
264
|
+
* anchoring on a foreign block would split somebody else's work.
|
|
265
|
+
*/
|
|
266
|
+
export function lastTiledBlock(window: any): string | undefined {
|
|
267
|
+
for (const layer of window?.layers ?? []) {
|
|
268
|
+
const blocks = layoutBlocks(layer?.layout);
|
|
269
|
+
if (blocks.length > 0) return blocks[blocks.length - 1];
|
|
270
|
+
}
|
|
271
|
+
return typeof window?.focused_block_id === "string" ? window.focused_block_id : undefined;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Resolve one window's layout + anchor from `rex session inspect`. */
|
|
275
|
+
async function inspectWindow(
|
|
276
|
+
exec: HerdrExec,
|
|
277
|
+
windowId: string,
|
|
278
|
+
): Promise<{ anchor: string; blocks: string[] } | undefined> {
|
|
279
|
+
const session = process.env.REX_SESSION;
|
|
280
|
+
if (!session) return undefined;
|
|
281
|
+
// `session inspect` takes the session POSITIONALLY and rejects the global
|
|
282
|
+
// `-s` prefix (`unknown shorthand flag: 's'`) — so this one call bypasses
|
|
283
|
+
// rexJson's session scoping. Every OTHER command takes -s.
|
|
284
|
+
const res = await exec(REX_BIN, ["session", "inspect", session, "--json"], { timeout: 20_000 });
|
|
285
|
+
if (res.code !== 0) return undefined;
|
|
286
|
+
let data: any;
|
|
287
|
+
try {
|
|
288
|
+
data = JSON.parse(res.stdout.trim());
|
|
289
|
+
} catch {
|
|
290
|
+
return undefined;
|
|
291
|
+
}
|
|
292
|
+
const window = (data?.windows ?? []).find((w: any) => w?.window_id === windowId);
|
|
293
|
+
if (!window) return undefined;
|
|
294
|
+
const blocks = (window.layers ?? []).flatMap((layer: any) => layoutBlocks(layer?.layout));
|
|
295
|
+
const anchor = lastTiledBlock(window);
|
|
296
|
+
return anchor ? { anchor, blocks } : undefined;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ---------------------------------------------------------------------------
|
|
300
|
+
// Child argv — pi contract from the herdr backends + env wrapper
|
|
301
|
+
// ---------------------------------------------------------------------------
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* The command a rex block runs: `/usr/bin/env VAR=… pi <flags>`.
|
|
305
|
+
*
|
|
306
|
+
* argv[0] is the PROGRAM (a rex block execs the command directly, like the
|
|
307
|
+
* herdr-app launcher), and `env` is the one portable way to hand a Rex child
|
|
308
|
+
* environment variables — Rex's split/window-new take no --env. That buys the
|
|
309
|
+
* rex backend two things the herdr-app path cannot do: the advisor review
|
|
310
|
+
* marker (so the parent waits for the child's own advisor before collecting)
|
|
311
|
+
* and the recursion guard (`PI_SUBAGENT_HERDR=off`, which also disables rex
|
|
312
|
+
* delegation in the child).
|
|
313
|
+
*/
|
|
314
|
+
export function buildRexCommand(opts: { piArgs: string[]; advisorMarker: string }): string[] {
|
|
315
|
+
return [
|
|
316
|
+
"/usr/bin/env",
|
|
317
|
+
`${HERDR_OFF_ENV}=off`,
|
|
318
|
+
"CEULEN_THINK_GATE_OFF=1",
|
|
319
|
+
`${ADVISOR_MARKER_ENV}=${opts.advisorMarker}`,
|
|
320
|
+
"pi",
|
|
321
|
+
...opts.piArgs,
|
|
322
|
+
];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ---------------------------------------------------------------------------
|
|
326
|
+
// Terminal state
|
|
327
|
+
// ---------------------------------------------------------------------------
|
|
328
|
+
|
|
329
|
+
export interface RexTerminal {
|
|
330
|
+
address: string;
|
|
331
|
+
status: HerdrAgentState;
|
|
332
|
+
app: string | null;
|
|
333
|
+
state: "live" | "finished" | "unknown";
|
|
334
|
+
cwd?: string;
|
|
335
|
+
/** Root status record's clock (ms) — the turn proof. */
|
|
336
|
+
statusAt?: number;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function mapStatus(raw: unknown): HerdrAgentState {
|
|
340
|
+
return raw === "idle" || raw === "done" || raw === "blocked" || raw === "working" ? raw : "unknown";
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Root record only: child records report their own sub-statuses and must
|
|
344
|
+
* never be read as the program's lifecycle (herdr-app's `hc get` parity). */
|
|
345
|
+
export async function getRexTerminal(address: string, exec: HerdrExec): Promise<RexTerminal | undefined> {
|
|
346
|
+
const [status, proc] = await Promise.all([
|
|
347
|
+
blockCall(exec, address, "program_status", undefined, 10_000),
|
|
348
|
+
blockCall(exec, address, "process", undefined, 10_000),
|
|
349
|
+
]);
|
|
350
|
+
if (!status.ok && !proc.ok) return undefined;
|
|
351
|
+
const records: any[] = status.ok ? (status.data?.records ?? []) : [];
|
|
352
|
+
const root = records.find((r: any) => r?.id === undefined) ?? records[0];
|
|
353
|
+
const statusAt = root?.updated_at ? Date.parse(String(root.updated_at)) : undefined;
|
|
354
|
+
const lastExit = proc.ok ? proc.data?.last_exit : undefined;
|
|
355
|
+
return {
|
|
356
|
+
address,
|
|
357
|
+
status: mapStatus(root?.state),
|
|
358
|
+
app: typeof root?.app === "string" ? root.app : null,
|
|
359
|
+
// A reported `last_exit` means the block's program ended.
|
|
360
|
+
state: proc.ok ? (lastExit ? "finished" : "live") : "unknown",
|
|
361
|
+
cwd: proc.ok ? proc.data?.foreground?.cwd : undefined,
|
|
362
|
+
statusAt: Number.isFinite(statusAt) ? statusAt : undefined,
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Settled = idle/done, and not a finished program. Unknown fails closed. */
|
|
367
|
+
function isSettled(t: RexTerminal | undefined): boolean {
|
|
368
|
+
if (!t) return false;
|
|
369
|
+
return t.state === "live" && (t.status === "idle" || t.status === "done");
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// ---------------------------------------------------------------------------
|
|
373
|
+
// Prepare: validate + topology + spawn (no prompt)
|
|
374
|
+
// ---------------------------------------------------------------------------
|
|
375
|
+
|
|
376
|
+
export interface PrepareRexTaskOptions {
|
|
377
|
+
agentType: string;
|
|
378
|
+
systemPrompt: string;
|
|
379
|
+
task: string;
|
|
380
|
+
cwd: string;
|
|
381
|
+
model?: string;
|
|
382
|
+
thinking?: string;
|
|
383
|
+
tools?: string[];
|
|
384
|
+
readOnly?: boolean;
|
|
385
|
+
timeoutMs: number;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function resultFilePath(cwd: string, name: string, stamp: string): string {
|
|
389
|
+
return path.join(cwd, ".pi", "rex", `${name}-${stamp}.md`);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function advisorMarkerPath(cwd: string, stamp: string): string {
|
|
393
|
+
return path.join(cwd, ".pi", "rex", `${stamp}.advisor.json`);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Create the agent type's window, or adopt the one already labelled for it. */
|
|
397
|
+
async function ensureRexWindow(opts: {
|
|
398
|
+
exec: HerdrExec;
|
|
399
|
+
agentType: string;
|
|
400
|
+
cwd: string;
|
|
401
|
+
command: string[];
|
|
402
|
+
}): Promise<{ windowId: string; blockId: string; created: boolean }> {
|
|
403
|
+
const existing = (await listRexWindows(opts.exec)).find((w) => w.label === opts.agentType);
|
|
404
|
+
if (existing) {
|
|
405
|
+
const inspected = await inspectWindow(opts.exec, existing.windowId);
|
|
406
|
+
// Adopt with a known anchor when we can prove the layout; otherwise the
|
|
407
|
+
// caller falls back to a plain split beside the focused block.
|
|
408
|
+
return { windowId: existing.windowId, blockId: inspected?.anchor ?? "", created: false };
|
|
409
|
+
}
|
|
410
|
+
// The window label is a POSITIONAL argument (not a flag); `--` separates it
|
|
411
|
+
// from the command so a label can never be read as one.
|
|
412
|
+
const created = await rexJson(
|
|
413
|
+
opts.exec,
|
|
414
|
+
["window", "new", opts.agentType, "-c", opts.cwd, "--focus=false", "--json", "--", ...opts.command],
|
|
415
|
+
60_000,
|
|
416
|
+
);
|
|
417
|
+
if (!created.ok) throw new Error(`rex window new failed: ${created.error}`);
|
|
418
|
+
const windowId = created.data?.window_id;
|
|
419
|
+
const blockId = created.data?.block_ids?.[0];
|
|
420
|
+
if (typeof windowId !== "string" || typeof blockId !== "string") {
|
|
421
|
+
throw new Error("rex window new: unexpected response shape (missing window_id/block_ids)");
|
|
422
|
+
}
|
|
423
|
+
return { windowId, blockId, created: true };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** Split a new pane into an existing window beside `anchor`. */
|
|
427
|
+
async function splitRexPane(opts: {
|
|
428
|
+
exec: HerdrExec;
|
|
429
|
+
anchor: string;
|
|
430
|
+
label: string;
|
|
431
|
+
cwd: string;
|
|
432
|
+
command: string[];
|
|
433
|
+
direction: "right" | "below";
|
|
434
|
+
}): Promise<string> {
|
|
435
|
+
const split = await rexJson(
|
|
436
|
+
opts.exec,
|
|
437
|
+
[
|
|
438
|
+
"split", "-b", opts.anchor,
|
|
439
|
+
"--split", opts.direction,
|
|
440
|
+
"--label", opts.label,
|
|
441
|
+
"-c", opts.cwd,
|
|
442
|
+
"--focus=false",
|
|
443
|
+
"--json",
|
|
444
|
+
"--", ...opts.command,
|
|
445
|
+
],
|
|
446
|
+
60_000,
|
|
447
|
+
);
|
|
448
|
+
if (!split.ok) throw new Error(`rex split failed: ${split.error}`);
|
|
449
|
+
const blockId = split.data?.block_ids?.[0];
|
|
450
|
+
if (typeof blockId !== "string") throw new Error("rex split: unexpected response shape (missing block_ids)");
|
|
451
|
+
return blockId;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// ponytail: per-agent-type serialization (herdr prepareChains precedent) —
|
|
455
|
+
// two concurrent same-type dispatches would race window adoption and pane
|
|
456
|
+
// anchoring. The expensive part (prompt + run) stays parallel.
|
|
457
|
+
const prepareChains = new Map<string, Promise<RexHandle>>();
|
|
458
|
+
|
|
459
|
+
async function prepareRexTaskUncached(opts: PrepareRexTaskOptions): Promise<RexHandle> {
|
|
460
|
+
const exec = rexCli.exec;
|
|
461
|
+
if (Buffer.byteLength(opts.task, "utf8") > HERDR_TASK_BUDGET) {
|
|
462
|
+
throw new Error(`rex task exceeds the ${HERDR_TASK_BUDGET}-byte budget (delivery wrapper included) — shorten the task or use runner:"sdk".`);
|
|
463
|
+
}
|
|
464
|
+
const live = await listRexBlocks(exec);
|
|
465
|
+
const name = allocateName(opts.agentType, [
|
|
466
|
+
...live.map((b) => b.label),
|
|
467
|
+
...live.map((b) => b.blockId),
|
|
468
|
+
...registry.keys(),
|
|
469
|
+
]);
|
|
470
|
+
const stamp = dispatchStamp();
|
|
471
|
+
const handle: RexHandle = {
|
|
472
|
+
name,
|
|
473
|
+
agentType: opts.agentType,
|
|
474
|
+
tabId: "",
|
|
475
|
+
address: "",
|
|
476
|
+
paneId: "",
|
|
477
|
+
resultFile: resultFilePath(opts.cwd, name, stamp),
|
|
478
|
+
advisorMarker: advisorMarkerPath(opts.cwd, stamp),
|
|
479
|
+
task: opts.task,
|
|
480
|
+
readOnly: opts.readOnly,
|
|
481
|
+
model: opts.model ?? "",
|
|
482
|
+
thinking: opts.thinking,
|
|
483
|
+
timeoutMs: opts.timeoutMs,
|
|
484
|
+
tabCreatedHere: true,
|
|
485
|
+
};
|
|
486
|
+
registry.set(name, handle);
|
|
487
|
+
try {
|
|
488
|
+
await fs.mkdir(path.dirname(handle.resultFile), { recursive: true });
|
|
489
|
+
const systemPromptFile = path.join(path.dirname(handle.resultFile), `${name}.system.md`);
|
|
490
|
+
await fs.writeFile(systemPromptFile, opts.systemPrompt, "utf8");
|
|
491
|
+
// Build argv BEFORE topology: a validation failure (read-only sandbox with
|
|
492
|
+
// no allowed tools) must leave no orphan window behind.
|
|
493
|
+
const piArgs = buildPiArgs({
|
|
494
|
+
name,
|
|
495
|
+
systemPromptFile,
|
|
496
|
+
model: opts.model,
|
|
497
|
+
thinking: opts.thinking,
|
|
498
|
+
tools: opts.tools,
|
|
499
|
+
readOnly: opts.readOnly,
|
|
500
|
+
sessionStamp: stamp,
|
|
501
|
+
});
|
|
502
|
+
const command = buildRexCommand({ piArgs, advisorMarker: handle.advisorMarker });
|
|
503
|
+
|
|
504
|
+
const spawned = await ensureRexWindow({ exec, agentType: opts.agentType, cwd: opts.cwd, command });
|
|
505
|
+
handle.tabId = spawned.windowId;
|
|
506
|
+
handle.tabCreatedHere = spawned.created;
|
|
507
|
+
if (spawned.created) {
|
|
508
|
+
handle.address = spawned.blockId;
|
|
509
|
+
handle.paneId = spawned.blockId;
|
|
510
|
+
} else {
|
|
511
|
+
// Adopted window: add a pane beside its last tiled block so this
|
|
512
|
+
// dispatch's work is visible without disturbing existing panes.
|
|
513
|
+
const anchor = spawned.blockId || (await inspectWindow(exec, spawned.windowId))?.anchor;
|
|
514
|
+
if (!anchor) {
|
|
515
|
+
throw new Error(`rex: window "${opts.agentType}" has no block to split beside — open a shell in it, or use runner:"sdk".`);
|
|
516
|
+
}
|
|
517
|
+
const direction = (await listRexBlocks(exec)).filter((b) => b.windowId === spawned.windowId).length % 2 === 1 ? "right" : "below";
|
|
518
|
+
const blockId = await splitRexPane({ exec, anchor, label: name, cwd: opts.cwd, command, direction });
|
|
519
|
+
handle.address = blockId;
|
|
520
|
+
handle.paneId = blockId;
|
|
521
|
+
}
|
|
522
|
+
return handle;
|
|
523
|
+
} catch (err) {
|
|
524
|
+
registry.delete(handle.name);
|
|
525
|
+
throw err;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export function prepareRexTask(opts: PrepareRexTaskOptions): Promise<RexHandle> {
|
|
530
|
+
const prev = prepareChains.get(opts.agentType) ?? Promise.resolve(null as unknown as RexHandle);
|
|
531
|
+
const job = prev.then(
|
|
532
|
+
() => prepareRexTaskUncached(opts),
|
|
533
|
+
() => prepareRexTaskUncached(opts),
|
|
534
|
+
);
|
|
535
|
+
prepareChains.set(opts.agentType, job);
|
|
536
|
+
job.catch(() => { /* stored chain must not reject unhandled */ });
|
|
537
|
+
return job;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// ---------------------------------------------------------------------------
|
|
541
|
+
// Prompt + wait
|
|
542
|
+
// ---------------------------------------------------------------------------
|
|
543
|
+
|
|
544
|
+
/** Task + delivery contract (identical wording to the herdr backends). */
|
|
545
|
+
export function wrapRexTaskPrompt(task: string, resultFile: string, readOnly = false): string {
|
|
546
|
+
if (readOnly) {
|
|
547
|
+
return (
|
|
548
|
+
`${task}\n\n---\n` +
|
|
549
|
+
`Delivery: this session has read-only tools — do NOT write any files. ` +
|
|
550
|
+
`Reply with your full final report as your final message.`
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
return (
|
|
554
|
+
`${task}\n\n---\n` +
|
|
555
|
+
`Delivery: when your task is complete, write your full final report as Markdown to \`${resultFile}\` ` +
|
|
556
|
+
`(create parent directories if needed), then reply with a one-line summary only. ` +
|
|
557
|
+
`If follow-up feedback arrives after delivery (e.g. an advisor review), apply it and update the report file to the corrected version.`
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Submit the task and wait for that turn to settle.
|
|
565
|
+
*
|
|
566
|
+
* Rex offers no primitive that follows a program's turn (`rex wait` waits for
|
|
567
|
+
* an EXIT), so this is built from `program_status` polling — the hc `--wait`
|
|
568
|
+
* policy re-implemented:
|
|
569
|
+
*
|
|
570
|
+
* 1. Readiness gate: `send` pastes into whatever is on screen, so wait for a
|
|
571
|
+
* live `pi` reporting idle/done before pasting (a paste into a booting
|
|
572
|
+
* composer is lost while the caller sees a settled state).
|
|
573
|
+
* 2. Paste + Enter as two calls (`block send` types without executing).
|
|
574
|
+
* 3. Settle on done, on idle/done with a FRESH status timestamp, or on
|
|
575
|
+
* blocked. Freshness is the turn proof: a paste that never submitted
|
|
576
|
+
* leaves pi at its previous state AND timestamp (live-probed), so an
|
|
577
|
+
* unchanged timestamp after the grace window is reported as "pasted but
|
|
578
|
+
* never submitted" rather than collected as a success.
|
|
579
|
+
*/
|
|
580
|
+
export async function promptRexAndWait(opts: {
|
|
581
|
+
address: string;
|
|
582
|
+
text: string;
|
|
583
|
+
timeoutMs: number;
|
|
584
|
+
exec: HerdrExec;
|
|
585
|
+
signal?: AbortSignal;
|
|
586
|
+
}): Promise<PromptOutcome> {
|
|
587
|
+
if (opts.signal?.aborted) {
|
|
588
|
+
return { state: "unknown", delivered: false, error: "aborted: parent operation aborted" };
|
|
589
|
+
}
|
|
590
|
+
const ready = await waitForReady(opts.address, opts.exec, opts.signal);
|
|
591
|
+
if (!ready.ok) return { state: ready.state, delivered: false, error: ready.error };
|
|
592
|
+
const baseline = ready.statusAt;
|
|
593
|
+
|
|
594
|
+
const sent = await rexJson(opts.exec, ["block", "send", "-b", opts.address, opts.text], 60_000);
|
|
595
|
+
if (!sent.ok) return { state: ready.state, delivered: false, error: `rex block send failed: ${sent.error}` };
|
|
596
|
+
const entered = await rexJson(opts.exec, ["block", "send-key", "-b", opts.address, "enter"], 20_000);
|
|
597
|
+
if (!entered.ok) return { state: ready.state, delivered: false, error: `rex block send-key failed: ${entered.error}` };
|
|
598
|
+
|
|
599
|
+
const deadline = Date.now() + opts.timeoutMs;
|
|
600
|
+
const graceUntil = Date.now() + rexTiming.unsentGraceMs;
|
|
601
|
+
let sawWorking = false;
|
|
602
|
+
let last: RexTerminal | undefined;
|
|
603
|
+
for (;;) {
|
|
604
|
+
if (opts.signal?.aborted) {
|
|
605
|
+
await cancelRexAgent(opts.address, opts.exec);
|
|
606
|
+
return { state: "unknown", delivered: true, error: "aborted: parent operation aborted" };
|
|
607
|
+
}
|
|
608
|
+
last = await getRexTerminal(opts.address, opts.exec);
|
|
609
|
+
const state = last?.status ?? "unknown";
|
|
610
|
+
const fresh = last?.statusAt !== undefined && (baseline === undefined || last.statusAt > baseline);
|
|
611
|
+
if (state === "working" || state === "blocked") sawWorking = true;
|
|
612
|
+
if (state === "blocked") {
|
|
613
|
+
return { state, delivered: false, error: "Agent is blocked on a dialog — answer it in its pane, then prompt again." };
|
|
614
|
+
}
|
|
615
|
+
// A turn ran (fresh timestamp) and settled, or we watched it work first.
|
|
616
|
+
if ((state === "done" || state === "idle") && (fresh || sawWorking)) {
|
|
617
|
+
return { state, delivered: true };
|
|
618
|
+
}
|
|
619
|
+
if (!sawWorking && !fresh && Date.now() >= graceUntil) {
|
|
620
|
+
return {
|
|
621
|
+
state,
|
|
622
|
+
delivered: false,
|
|
623
|
+
error: "the task was pasted but never submitted (no fresh status since the paste) — the child was not ready or a dialog holds the composer; prompt it again in its pane",
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
if (Date.now() >= deadline) {
|
|
627
|
+
return { state, delivered: true, error: `timeout after ${opts.timeoutMs}ms` };
|
|
628
|
+
}
|
|
629
|
+
await sleep(rexTiming.pollMs);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** Poll until a live, input-ready pi answers. `done` counts as ready — pi
|
|
634
|
+
* reports it for a turn that finished unwatched, and that composer takes
|
|
635
|
+
* input exactly like `idle`. */
|
|
636
|
+
async function waitForReady(
|
|
637
|
+
address: string,
|
|
638
|
+
exec: HerdrExec,
|
|
639
|
+
signal?: AbortSignal,
|
|
640
|
+
): Promise<{ ok: true; statusAt?: number; state: HerdrAgentState } | { ok: false; state: HerdrAgentState; error: string }> {
|
|
641
|
+
const deadline = Date.now() + rexTiming.readyTimeoutMs;
|
|
642
|
+
let last: RexTerminal | undefined;
|
|
643
|
+
for (;;) {
|
|
644
|
+
if (signal?.aborted) return { ok: false, state: "unknown", error: "aborted: parent operation aborted" };
|
|
645
|
+
last = await getRexTerminal(address, exec);
|
|
646
|
+
if (last?.state === "finished") {
|
|
647
|
+
return { ok: false, state: "unknown", error: "the child terminal exited before its task was sent" };
|
|
648
|
+
}
|
|
649
|
+
if (last?.app === "pi" && (last.status === "idle" || last.status === "done")) {
|
|
650
|
+
return { ok: true, statusAt: last.statusAt, state: last.status };
|
|
651
|
+
}
|
|
652
|
+
if (Date.now() >= deadline) {
|
|
653
|
+
return {
|
|
654
|
+
ok: false,
|
|
655
|
+
state: last?.status ?? "unknown",
|
|
656
|
+
error: `the child did not become ready for input within ${Math.round(rexTiming.readyTimeoutMs / 1000)}s${last?.status ? ` (last state: ${last.status})` : ""} — check its pane`,
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
await sleep(rexTiming.pollMs);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// ---------------------------------------------------------------------------
|
|
664
|
+
// Collection & cancel
|
|
665
|
+
// ---------------------------------------------------------------------------
|
|
666
|
+
|
|
667
|
+
/** Tail of a block's scrollback. `format` returns a HEAD slice (plus an id
|
|
668
|
+
* when more remains), so the end is re-read through `blob_read` at
|
|
669
|
+
* `total - N`; asking for the whole 64 MiB scrollback would park megabytes in
|
|
670
|
+
* the parent's context. */
|
|
671
|
+
export async function readRexBlock(
|
|
672
|
+
address: string,
|
|
673
|
+
exec: HerdrExec,
|
|
674
|
+
maxBytes = PANE_TAIL_BYTES,
|
|
675
|
+
): Promise<{ ok: boolean; text: string }> {
|
|
676
|
+
const head = await blockCall(exec, address, "format", { format: "text", trim: true, unwrap: true, max_bytes: 512 }, 20_000);
|
|
677
|
+
if (!head.ok) return { ok: false, text: head.error };
|
|
678
|
+
const content: string = head.data?.content ?? "";
|
|
679
|
+
const total: number = typeof head.data?.total === "number" ? head.data.total : 0;
|
|
680
|
+
const id = head.data?.id;
|
|
681
|
+
// `format` answers a HEAD slice, and an `id` in the reply means more output
|
|
682
|
+
// remains — so ANY reply carrying an id must be re-read from the END of the
|
|
683
|
+
// scrollback. (Comparing `total` against the cap instead was the bug: a
|
|
684
|
+
// 892-byte pane still came back as the boot chrome head, and the reply the
|
|
685
|
+
// child actually wrote was never fetched — live 2026-11-18.)
|
|
686
|
+
if (typeof id !== "number") return { ok: true, text: content };
|
|
687
|
+
const tail = await blockCall(
|
|
688
|
+
exec,
|
|
689
|
+
address,
|
|
690
|
+
"blob_read",
|
|
691
|
+
{ id, offset: Math.max(0, total - maxBytes), max_bytes: Math.min(maxBytes, 983_040) },
|
|
692
|
+
20_000,
|
|
693
|
+
);
|
|
694
|
+
if (tail.ok && typeof tail.data?.data === "string") return { ok: true, text: tail.data.data };
|
|
695
|
+
return { ok: true, text: content };
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* The pane's reply, or "" when the pane holds nothing but our echoed task.
|
|
700
|
+
* Strategy is the herdr-app one — the reply always comes AFTER our own text,
|
|
701
|
+
* so cut rather than subtract: find the delivery contract (or the task) and
|
|
702
|
+
* keep the tail. Best effort by design; a genuinely fresh turn keeps the raw
|
|
703
|
+
* tail when neither marker survives TUI wrapping.
|
|
704
|
+
*/
|
|
705
|
+
export function replyBeyondEcho(paneText: string, task: string): string {
|
|
706
|
+
const norm = (s: string) => s.replace(/\s+/g, " ").trim();
|
|
707
|
+
const flat = norm(paneText);
|
|
708
|
+
const contractEnd = (() => {
|
|
709
|
+
const re = /Delivery: [\s\S]*?(?:corrected version\.|final message\.)/g;
|
|
710
|
+
let last = -1;
|
|
711
|
+
for (const m of flat.matchAll(re)) last = (m.index ?? 0) + m[0].length;
|
|
712
|
+
return last;
|
|
713
|
+
})();
|
|
714
|
+
const cut = contractEnd >= 0 ? flat.slice(contractEnd) : (() => {
|
|
715
|
+
const at = task ? flat.indexOf(norm(task)) : -1;
|
|
716
|
+
return at >= 0 ? flat.slice(at + norm(task).length) : flat;
|
|
717
|
+
})();
|
|
718
|
+
return cut
|
|
719
|
+
.replace(/\u2191[\d.]+K?\s*\u2193[\d.]+[\s\S]*$/g, "")
|
|
720
|
+
.replace(/[\u03c0]\s*>.*$/g, "")
|
|
721
|
+
.replace(/^\s*[\u2570\u2500]+.*$/g, "")
|
|
722
|
+
.trim();
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** Report file first (delivery contract), pane tail as best-effort fallback. */
|
|
726
|
+
export async function collectRexResult(opts: {
|
|
727
|
+
handle: RexHandle;
|
|
728
|
+
exec: HerdrExec;
|
|
729
|
+
}): Promise<{ output: string; source: "file" | "pane" | "none" }> {
|
|
730
|
+
const fromFile = await readReportFile(opts.handle.resultFile);
|
|
731
|
+
if (fromFile) return { output: fromFile, source: "file" };
|
|
732
|
+
const read = await readRexBlock(opts.handle.address, opts.exec);
|
|
733
|
+
if (!read.ok) return { output: "", source: "none" };
|
|
734
|
+
const lines = read.text.split("\n").slice(-200).join("\n");
|
|
735
|
+
const reply = replyBeyondEcho(lines, opts.handle.task);
|
|
736
|
+
// An echo-only capture is NOT a reply — report no output so the caller fails
|
|
737
|
+
// loudly instead of returning the task back as a successful report.
|
|
738
|
+
if (!reply || norm0(reply) === norm0(opts.handle.task)) return { output: "", source: "none" };
|
|
739
|
+
return { output: capPaneCapture(reply), source: "pane" };
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
const norm0 = (s: string) => s.replace(/\s+/g, " ").trim();
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* Interrupt a delegated agent: esc (pi's interrupt), then ctrl+c when the
|
|
746
|
+
* terminal is not verifiably settled — herdr's escalation shape.
|
|
747
|
+
*/
|
|
748
|
+
export async function cancelRexAgent(address: string, exec: HerdrExec = rexCli.exec): Promise<void> {
|
|
749
|
+
const esc = await rexJson(exec, ["block", "send-key", "-b", address, "esc"], 10_000);
|
|
750
|
+
if (!esc.ok) return;
|
|
751
|
+
await sleep(500);
|
|
752
|
+
try {
|
|
753
|
+
const info = await getRexTerminal(address, exec);
|
|
754
|
+
if (!isSettled(info)) await rexJson(exec, ["block", "send-key", "-b", address, "ctrl+c"], 10_000);
|
|
755
|
+
} catch { /* best effort */ }
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// ---------------------------------------------------------------------------
|
|
759
|
+
// High-level flow
|
|
760
|
+
// ---------------------------------------------------------------------------
|
|
761
|
+
|
|
762
|
+
export interface ExecuteRexTaskOptions {
|
|
763
|
+
exec?: HerdrExec;
|
|
764
|
+
onState?: (state: string) => void;
|
|
765
|
+
signal?: AbortSignal;
|
|
766
|
+
advisorWaitMs?: number;
|
|
767
|
+
onAdvisorPhase?: (phase: string) => void;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** Prompt the prepared agent, wait for settle, collect the report. */
|
|
771
|
+
export async function executeRexTask(
|
|
772
|
+
handle: RexHandle,
|
|
773
|
+
opts: ExecuteRexTaskOptions = {},
|
|
774
|
+
): Promise<SubAgentResult> {
|
|
775
|
+
const exec = opts.exec ?? rexCli.exec;
|
|
776
|
+
const startedAt = Date.now();
|
|
777
|
+
let pollTimer: ReturnType<typeof setInterval> | undefined;
|
|
778
|
+
let lastState = "";
|
|
779
|
+
let pollInFlight = false;
|
|
780
|
+
const poll = async () => {
|
|
781
|
+
if (pollInFlight) return;
|
|
782
|
+
pollInFlight = true;
|
|
783
|
+
try {
|
|
784
|
+
const state = (await getRexTerminal(handle.address, exec))?.status ?? "unknown";
|
|
785
|
+
if (state !== lastState) {
|
|
786
|
+
lastState = state;
|
|
787
|
+
opts.onState?.(state);
|
|
788
|
+
}
|
|
789
|
+
} catch { /* state poll is best-effort */ }
|
|
790
|
+
pollInFlight = false;
|
|
791
|
+
};
|
|
792
|
+
try {
|
|
793
|
+
pollTimer = setInterval(() => { void poll(); }, 2_000);
|
|
794
|
+
pollTimer.unref?.();
|
|
795
|
+
const prompt = await promptRexAndWait({
|
|
796
|
+
address: handle.address,
|
|
797
|
+
text: wrapRexTaskPrompt(handle.task, handle.resultFile, handle.readOnly),
|
|
798
|
+
timeoutMs: handle.timeoutMs,
|
|
799
|
+
exec,
|
|
800
|
+
signal: opts.signal,
|
|
801
|
+
});
|
|
802
|
+
let output = "";
|
|
803
|
+
let outputSource: "file" | "pane" | "none" = "none";
|
|
804
|
+
let advisorRounds = 0;
|
|
805
|
+
const aborted = Boolean(opts.signal?.aborted);
|
|
806
|
+
const timedOut = !aborted && Boolean(prompt.error && /timeout/.test(prompt.error));
|
|
807
|
+
if (timedOut) {
|
|
808
|
+
await cancelRexAgent(handle.address, exec);
|
|
809
|
+
prompt.error = `${prompt.error} (pane interrupted; it may still complete its current write — check ${path.basename(handle.resultFile)} or the pane before re-dispatching)`;
|
|
810
|
+
} else if (!aborted) {
|
|
811
|
+
advisorRounds = await awaitAdvisorCycle({
|
|
812
|
+
name: handle.address,
|
|
813
|
+
markerFile: handle.advisorMarker,
|
|
814
|
+
advisorWaitMs: opts.advisorWaitMs ?? 0,
|
|
815
|
+
signal: opts.signal,
|
|
816
|
+
onPhase: opts.onAdvisorPhase,
|
|
817
|
+
getState: async () => (await getRexTerminal(handle.address, exec))?.status ?? "unknown",
|
|
818
|
+
});
|
|
819
|
+
const collected = await collectRexResult({ handle, exec });
|
|
820
|
+
output = collected.output;
|
|
821
|
+
outputSource = collected.source;
|
|
822
|
+
}
|
|
823
|
+
const result = buildHerdrResult(
|
|
824
|
+
{
|
|
825
|
+
name: handle.name,
|
|
826
|
+
agentType: handle.agentType,
|
|
827
|
+
tabId: handle.tabId,
|
|
828
|
+
paneId: handle.paneId,
|
|
829
|
+
resultFile: handle.resultFile,
|
|
830
|
+
advisorMarker: handle.advisorMarker,
|
|
831
|
+
task: handle.task,
|
|
832
|
+
readOnly: handle.readOnly,
|
|
833
|
+
model: handle.model,
|
|
834
|
+
thinking: handle.thinking,
|
|
835
|
+
timeoutMs: handle.timeoutMs,
|
|
836
|
+
tabCreatedHere: handle.tabCreatedHere,
|
|
837
|
+
},
|
|
838
|
+
{
|
|
839
|
+
state: prompt.state,
|
|
840
|
+
delivered: prompt.delivered,
|
|
841
|
+
error: prompt.error,
|
|
842
|
+
output,
|
|
843
|
+
outputSource,
|
|
844
|
+
durationMs: Date.now() - startedAt,
|
|
845
|
+
},
|
|
846
|
+
);
|
|
847
|
+
// Pane identity rides the usage line (herdr precedent) — rex: not herdr:.
|
|
848
|
+
result.model = (result.model ?? "").replace(" · herdr pane:", " · rex pane:");
|
|
849
|
+
if (advisorRounds > 0) result.advisorRounds = advisorRounds;
|
|
850
|
+
if (aborted) {
|
|
851
|
+
result.stopReason = "aborted";
|
|
852
|
+
result.status = "aborted";
|
|
853
|
+
result.exitCode = 1;
|
|
854
|
+
result.errorMessage = "Cancelled: parent operation aborted";
|
|
855
|
+
}
|
|
856
|
+
return result;
|
|
857
|
+
} finally {
|
|
858
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// ---------------------------------------------------------------------------
|
|
863
|
+
// Layout helpers for the control tool
|
|
864
|
+
// ---------------------------------------------------------------------------
|
|
865
|
+
|
|
866
|
+
/** Busy siblings in a window (closing it kills every pane in it). */
|
|
867
|
+
export async function rexWindowCloseBlockers(
|
|
868
|
+
handle: RexHandle,
|
|
869
|
+
exec: HerdrExec,
|
|
870
|
+
): Promise<{ siblings: string[]; self: string | undefined }> {
|
|
871
|
+
const siblings: string[] = [];
|
|
872
|
+
for (const entry of registry.values()) {
|
|
873
|
+
if (entry.tabId !== handle.tabId || entry.address === handle.address) continue;
|
|
874
|
+
const info = await getRexTerminal(entry.address, exec);
|
|
875
|
+
// Fail closed: only an observed settled state proves the sibling is free.
|
|
876
|
+
if (!isSettled(info)) siblings.push(entry.name);
|
|
877
|
+
}
|
|
878
|
+
const selfInfo = await getRexTerminal(handle.address, exec);
|
|
879
|
+
const self = selfInfo && !isSettled(selfInfo) ? selfInfo.status ?? "unknown" : undefined;
|
|
880
|
+
return { siblings, self };
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** Raise the agent's window in the Rex app. */
|
|
884
|
+
export async function focusRexWindow(windowId: string, exec: HerdrExec): Promise<{ ok: boolean; error?: string }> {
|
|
885
|
+
const res = await rexJson(exec, ["focus", windowId], 15_000);
|
|
886
|
+
return res.ok ? { ok: true } : { ok: false, error: res.error };
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** Close a window this session created (and the panes in it). */
|
|
890
|
+
export async function closeRexWindow(windowId: string, exec: HerdrExec): Promise<{ ok: boolean; error?: string }> {
|
|
891
|
+
const res = await rexJson(exec, ["window", "close", windowId], 30_000);
|
|
892
|
+
return res.ok ? { ok: true } : { ok: false, error: res.error };
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/** Submit a follow-up prompt without waiting (control tool, wait:false). */
|
|
896
|
+
export async function sendRexPrompt(address: string, text: string, exec: HerdrExec): Promise<{ ok: boolean; error?: string }> {
|
|
897
|
+
const send = await rexJson(exec, ["block", "send", "-b", address, text], 60_000);
|
|
898
|
+
if (!send.ok) return { ok: false, error: send.error };
|
|
899
|
+
const enter = await rexJson(exec, ["block", "send-key", "-b", address, "enter"], 20_000);
|
|
900
|
+
return enter.ok ? { ok: true } : { ok: false, error: enter.error };
|
|
901
|
+
}
|
|
902
|
+
|