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.
@@ -0,0 +1,917 @@
1
+ /**
2
+ * herdr-app delegation backend for the subagent module.
3
+ *
4
+ * herdr-TUI delegation (lib/herdr.ts) drives the `herdr` CLI from inside a
5
+ * herdr managed pane (`HERDR_ENV=1`). The herdr DESKTOP app is a different
6
+ * pair of programs: the app arranges windows (`herdr-app`), herdr-core (`hc`)
7
+ * runs the terminals. Pi inside an app pane has `HC_TERMINAL_ID` and no
8
+ * `HERDR_ENV`, so herdr.ts never fires.
9
+ *
10
+ * Topology mirrors the TUI backend so the model's mental model carries over:
11
+ *
12
+ * - One TAB per agent type (created with `herdr-app do tab.new --argv
13
+ * '["pi", …]'`), adopted when a tab of that label already exists.
14
+ * - One PANE per agent instance (`pane.split`), one terminal each.
15
+ * - Every terminal is an `hc` terminal: `hc send --wait` submits the task and
16
+ * follows THAT turn (herdr-core's real OSC 7501 status — no TUI stall
17
+ * workaround is needed here), `hc read` collects, `hc interrupt` stops.
18
+ * - Results come back via the same file contract as the TUI backend (pi
19
+ * renders on the alternate screen; read-only children reply inline).
20
+ *
21
+ * All CLI calls go through an injectable `exec` (the `herdrAppCli` seam, the
22
+ * herdr.ts `herdrCli` precedent) so tests script both binaries.
23
+ */
24
+
25
+ import * as fs from "node:fs/promises";
26
+ import * as path from "node:path";
27
+ import { ADVISOR_MARKER_ENV } from "../../../lib/advisor-marker.js";
28
+ import {
29
+ allocateName,
30
+ awaitAdvisorCycle,
31
+ buildHerdrResult,
32
+ capPaneCapture,
33
+ dispatchStamp,
34
+ HERDR_OFF_ENV,
35
+ HERDR_TASK_BUDGET,
36
+ MAX_REPORT_BYTES,
37
+ readReportFile,
38
+ type HerdrAgentState,
39
+ type HerdrExec,
40
+ type PromptOutcome,
41
+ } from "./herdr.ts";
42
+ import { defaultExec, type SubAgentResult } from "./runner.ts";
43
+ import { buildPiArgs, type BuildPiArgsOptions } from "./herdr.ts";
44
+
45
+ /** The exec used by the app backend and control tool. Tests swap this. */
46
+ export const herdrAppCli: { exec: HerdrExec } = { exec: defaultExec };
47
+
48
+ /** Binary names, resolved on PATH (the user may symlink either). */
49
+ const APP_BIN = "herdr-app";
50
+ const HC_BIN = "hc";
51
+ /** How long a fresh app child may take to reach an input-ready idle pi.
52
+ * Cold model loading + extension startup are slow; the TUI backend waits
53
+ * inside `herdr agent start`, this is the app path's equivalent. */
54
+ const READY_TIMEOUT_MS = 120_000;
55
+
56
+ /**
57
+ * Detection: herdr-core stamps every terminal it runs with HC_TERMINAL_ID.
58
+ * That is strictly wider than "inside the app window" (an `hc run` terminal
59
+ * from a plain shell has it too) — deliberately, because delegation works
60
+ * from any herdr-core terminal, and the app is only needed for the layout
61
+ * commands (which fail loudly if no window is open).
62
+ */
63
+ export function herdrAppEnvDetected(): boolean {
64
+ return Boolean(process.env.HC_TERMINAL_ID);
65
+ }
66
+
67
+ /** Same kill-switch as the TUI backend: `subagent.herdr:"off"` disables
68
+ * delegation everywhere, and the child recursion guard is shared. */
69
+ export function herdrAppDisabled(subagentSettings?: { herdr?: unknown }): boolean {
70
+ if (subagentSettings?.herdr === "off") return true;
71
+ return process.env[HERDR_OFF_ENV] === "off";
72
+ }
73
+
74
+ let appProbe: Promise<boolean> | undefined;
75
+ let hcProbe: Promise<boolean> | undefined;
76
+
77
+ /** Both binaries must answer: the app for layout, hc for the terminal. */
78
+ export async function probeHerdrAppBinary(exec: HerdrExec = defaultExec): Promise<boolean> {
79
+ const cacheable = exec === defaultExec;
80
+ if (cacheable && appProbe && hcProbe) return (await appProbe) && (await hcProbe);
81
+ const app = (async () => {
82
+ const res = await exec(APP_BIN, ["--version"], { timeout: 5_000 });
83
+ const ok = res.code === 0;
84
+ // Cache successes only (herdr.ts precedent): a transient failure must not
85
+ // disable delegation for the process lifetime.
86
+ if (cacheable && ok) appProbe = Promise.resolve(true);
87
+ return ok;
88
+ })();
89
+ const hc = (async () => {
90
+ const res = await exec(HC_BIN, ["--version"], { timeout: 5_000 });
91
+ const ok = res.code === 0;
92
+ if (cacheable && ok) hcProbe = Promise.resolve(true);
93
+ return ok;
94
+ })();
95
+ return (await app) && (await hc);
96
+ }
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // Registry — session-scoped, one entry per dispatched tab
100
+ // ---------------------------------------------------------------------------
101
+
102
+ export interface HerdrAppHandle {
103
+ /** Tab label = agent type. Adopted tabs keep their label. */
104
+ tabName: string;
105
+ tabId: string;
106
+ /** hc terminal address ("t7") — the identity every hc command takes. */
107
+ address: string;
108
+ /** App pane id, when the app reported one ("" when only hc knows the terminal). */
109
+ paneId: string;
110
+ /** Allocated name; also passed to the child as pi --name for its title. */
111
+ name: string;
112
+ agentType: string;
113
+ task: string;
114
+ resultFile: string;
115
+ /** Advisor review-cycle sidecar (ADVISOR_MARKER_ENV), same contract as herdr.ts. */
116
+ advisorMarker: string;
117
+ readOnly?: boolean;
118
+ model: string;
119
+ thinking?: string;
120
+ timeoutMs: number;
121
+ /** False when the tab pre-existed (label match) — adopted tabs are never
122
+ * eligible for close-tab. */
123
+ tabCreatedHere: boolean;
124
+ }
125
+
126
+ /** Keyed by the UNIQUE agent name (herdr.ts precedent) — parallel dispatches of
127
+ * one agent type share a tab but must each stay addressable. */
128
+ const registry = new Map<string, HerdrAppHandle>();
129
+
130
+ export function getHerdrAppRegistry(): HerdrAppHandle[] {
131
+ return [...registry.values()];
132
+ }
133
+
134
+ /** Look up a handle by allocated name OR hc address (the control tool accepts
135
+ * either; `hc` does too). */
136
+ export function findHerdrAppAgent(nameOrAddress: string): HerdrAppHandle | undefined {
137
+ const direct = registry.get(nameOrAddress);
138
+ if (direct) return direct;
139
+ for (const entry of registry.values()) {
140
+ if (entry.address === nameOrAddress || entry.name === nameOrAddress) return entry;
141
+ }
142
+ return undefined;
143
+ }
144
+
145
+ export function isDelegatedHerdrAppAgent(nameOrAddress: string): boolean {
146
+ return Boolean(findHerdrAppAgent(nameOrAddress));
147
+ }
148
+
149
+ export function forgetHerdrAppTab(tabNameOrId: string): void {
150
+ for (const [key, entry] of registry) {
151
+ if (key === tabNameOrId || entry.tabId === tabNameOrId) registry.delete(key);
152
+ }
153
+ }
154
+
155
+ /** Test hook: reset the session registry. */
156
+ export function clearHerdrAppRegistry(): void {
157
+ registry.clear();
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // CLI plumbing
162
+ // ---------------------------------------------------------------------------
163
+
164
+ function firstLine(res: { stdout: string; stderr: string }): string {
165
+ return (res.stderr || res.stdout).trim().split("\n")[0]?.slice(0, 300) ?? "";
166
+ }
167
+
168
+ /** Parse a JSON payload; both CLIs answer `{…}` (sometimes wrapped in `result`). */
169
+ function parseJson(text: string): any | undefined {
170
+ try {
171
+ return JSON.parse(text);
172
+ } catch {
173
+ return undefined;
174
+ }
175
+ }
176
+
177
+ /** `hc … --json` → { ok, data } (errors are JSON on stderr with `kind`). */
178
+ async function hcJson(
179
+ exec: HerdrExec,
180
+ args: string[],
181
+ timeoutMs = 20_000,
182
+ ): Promise<{ ok: true; data: any } | { ok: false; error: string }> {
183
+ const res = await exec(HC_BIN, [...args, "--json"], { timeout: timeoutMs });
184
+ const data = parseJson(res.stdout.trim() || res.stderr.trim());
185
+ if (res.code !== 0) {
186
+ const message = data?.error?.message ?? firstLine(res) ?? `exit ${res.code}`;
187
+ return { ok: false, error: message };
188
+ }
189
+ return { ok: true, data: data ?? {} };
190
+ }
191
+
192
+ /** `herdr-app do <command> --key value…` → parsed reply (or its error). */
193
+ async function appDo(
194
+ exec: HerdrExec,
195
+ command: string,
196
+ args: Record<string, unknown> = {},
197
+ timeoutMs = 60_000,
198
+ ): Promise<{ ok: true; data: any } | { ok: false; error: string }> {
199
+ const cliArgs = ["do", command, JSON.stringify(args)];
200
+ const res = await exec(APP_BIN, cliArgs, { timeout: timeoutMs });
201
+ const data = parseJson(res.stdout.trim());
202
+ if (res.code !== 0 || (data && typeof data.error === "string")) {
203
+ return { ok: false, error: data?.error ?? firstLine(res) ?? `herdr-app ${command} failed (exit ${res.code})` };
204
+ }
205
+ return { ok: true, data: data ?? {} };
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // herdr-app layout: spaces, tabs, panes
210
+ // ---------------------------------------------------------------------------
211
+
212
+ export interface AppTab {
213
+ id: string;
214
+ name: string;
215
+ terminals: { terminal: string; pane: string; status?: string | null; app?: string | null }[];
216
+ }
217
+
218
+ export interface AppSpace {
219
+ id: string;
220
+ name: string;
221
+ machine: string | null;
222
+ tabs: AppTab[];
223
+ }
224
+
225
+ /** `herdr-app ls` → spaces (empty when no window answers). */
226
+ export async function listAppSpaces(exec: HerdrExec): Promise<AppSpace[]> {
227
+ const res = await exec(APP_BIN, ["ls"], { timeout: 20_000 });
228
+ const data = parseJson(res.stdout.trim());
229
+ if (res.code !== 0 || !data) return [];
230
+ return (data.spaces ?? []).map((s: any) => ({
231
+ id: s?.id,
232
+ name: s?.name ?? "",
233
+ machine: s?.machine ?? null,
234
+ tabs: (s?.tabs ?? []).map((t: any) => ({
235
+ id: t?.id,
236
+ name: t?.name ?? "",
237
+ terminals: (t?.terminals ?? []).map((x: any) => ({
238
+ terminal: x?.terminal,
239
+ pane: x?.pane,
240
+ status: x?.status ?? null,
241
+ app: x?.app ?? null,
242
+ })),
243
+ })),
244
+ })).filter((s: AppSpace) => Boolean(s.id));
245
+ }
246
+
247
+ /** The space holding the caller's own terminal (by its herdr.space label),
248
+ * else the first local space. Returns undefined when no window is open. */
249
+ async function resolveSpace(exec: HerdrExec, listed?: AppSpace[]): Promise<AppSpace | undefined> {
250
+ const spaces = listed ?? await listAppSpaces(exec);
251
+ if (spaces.length === 0) return undefined;
252
+ const ownId = process.env.HC_TERMINAL_ID;
253
+ if (ownId) {
254
+ const got = await hcJson(exec, ["get", ownId], 10_000);
255
+ const label = got.ok ? got.data?.labels?.["herdr.space"] : undefined;
256
+ if (typeof label === "string") {
257
+ const match = spaces.find((s) => s.id === label);
258
+ if (match) return match;
259
+ }
260
+ }
261
+ return spaces.find((s) => s.machine === null) ?? spaces[0];
262
+ }
263
+
264
+ /** Resolve the caller's space and any tab already labelled `agentType`. ONE
265
+ * `herdr-app ls` per prepare — the caller passes the list through. */
266
+ async function resolveSpaceAndTab(
267
+ exec: HerdrExec,
268
+ agentType: string,
269
+ ): Promise<{ spaces: AppSpace[]; space?: AppSpace; tab?: AppTab }> {
270
+ const spaces = await listAppSpaces(exec);
271
+ const space = await resolveSpace(exec, spaces);
272
+ const tab = space?.tabs.find((t) => t.name === agentType);
273
+ return { spaces, space, tab };
274
+ }
275
+
276
+ /** All live hc terminal names + addresses (dedupe baseline for allocateName). */
277
+ async function liveTerminalIds(exec: HerdrExec): Promise<string[]> {
278
+ const listed = await hcJson(exec, ["ls"], 15_000);
279
+ if (!listed.ok) return [];
280
+ const terminals: any[] = listed.data?.terminals ?? [];
281
+ const ids: string[] = [];
282
+ for (const t of terminals) {
283
+ if (typeof t?.address === "string") ids.push(t.address);
284
+ if (typeof t?.name === "string" && t.name) ids.push(t.name);
285
+ }
286
+ return ids;
287
+ }
288
+
289
+ // ---------------------------------------------------------------------------
290
+ // Child argv — TUI parity minus `--name` (hc carries the name instead)
291
+ // ---------------------------------------------------------------------------
292
+
293
+ /**
294
+ * The pi argv for an hc/app-launched child. Same persona/model/thinking/tools
295
+ * contract as the herdr-TUI child, with ONE herdr-app constraint: argv[0] must
296
+ * be the PROGRAM (the app's launcher runs `argv[0]` and forwards the rest),
297
+ * whereas buildPiArgs starts with flags for `herdr agent start --kind pi`.
298
+ */
299
+ export function buildAppPiArgs(opts: BuildPiArgsOptions): string[] {
300
+ return ["pi", ...buildPiArgs(opts)];
301
+ }
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // Terminal state
305
+ // ---------------------------------------------------------------------------
306
+
307
+ export interface HerdrAppTerminal {
308
+ address: string;
309
+ status: HerdrAgentState;
310
+ app: string | null;
311
+ state: "live" | "finished" | "unknown";
312
+ cwd?: string;
313
+ title?: string;
314
+ }
315
+
316
+ /** `hc get <t>` — real OSC 7501 status (unlike herdr 0.9.x pi panes). */
317
+ export async function getTerminal(address: string, exec: HerdrExec): Promise<HerdrAppTerminal | undefined> {
318
+ const got = await hcJson(exec, ["get", address], 10_000);
319
+ if (!got.ok) return undefined;
320
+ const t = got.data?.result ?? got.data;
321
+ const raw = t?.status?.state;
322
+ return {
323
+ address: t?.address ?? address,
324
+ status: raw === "idle" || raw === "done" || raw === "blocked" || raw === "working" ? raw : "unknown",
325
+ app: t?.status?.app ?? null,
326
+ state: t?.state === "live" || t?.state === "finished" ? t.state : "unknown",
327
+ cwd: t?.cwd,
328
+ title: t?.title,
329
+ };
330
+ }
331
+
332
+ /** Settled = idle/done/finished. Blocked/unknown fail closed (never "done"). */
333
+ function isSettled(t: HerdrAppTerminal | undefined): boolean {
334
+ if (!t) return false;
335
+ return t.state === "finished" || t.status === "idle" || t.status === "done";
336
+ }
337
+
338
+ // ---------------------------------------------------------------------------
339
+ // Prepare: validate + topology + spawn (no prompt)
340
+ // ---------------------------------------------------------------------------
341
+
342
+ export interface PrepareHerdrAppTaskOptions {
343
+ agentType: string;
344
+ systemPrompt: string;
345
+ task: string;
346
+ cwd: string;
347
+ model?: string;
348
+ thinking?: string;
349
+ tools?: string[];
350
+ readOnly?: boolean;
351
+ timeoutMs: number;
352
+ }
353
+
354
+ function resultFilePath(cwd: string, name: string, stamp: string): string {
355
+ return path.join(cwd, ".pi", "herdr-app", `${name}-${stamp}.md`);
356
+ }
357
+
358
+ function advisorMarkerPath(cwd: string, stamp: string): string {
359
+ return path.join(cwd, ".pi", "herdr-app", `${stamp}.advisor.json`);
360
+ }
361
+
362
+ /** Spawn the child in a NEW tab (the common path: one tab per agent type). */
363
+ async function spawnInNewTab(opts: {
364
+ exec: HerdrExec;
365
+ agentType: string;
366
+ spaceId: string;
367
+ cwd: string;
368
+ piArgs: string[];
369
+ advisorMarker: string;
370
+ }): Promise<{ tabId: string; address: string; paneId: string; created: boolean }> {
371
+ const created = await appDo(opts.exec, "tab.new", {
372
+ name: opts.agentType,
373
+ space: opts.spaceId,
374
+ folder: opts.cwd,
375
+ argv: opts.piArgs,
376
+ focus: false,
377
+ });
378
+ if (!created.ok) throw new Error(`herdr-app tab.new failed: ${created.error}`);
379
+ const tabId = created.data?.tab;
380
+ const address = created.data?.terminal;
381
+ if (!tabId || !address) {
382
+ throw new Error("herdr-app tab.new: unexpected response shape (missing tab/terminal)");
383
+ }
384
+ // ponytail: no ADVISOR_MARKER_ENV for app-spawned children — herdr-core only
385
+ // takes env at spawn via its JSON API, and neither `herdr-app tab.new` nor
386
+ // the `hc run` CLI exposes one. The child's advisor therefore publishes no
387
+ // marker, so awaitAdvisorCycle's grace poll returns 0 and collection happens
388
+ // at first settle (the TUI backend's skip-path behaviour). Wire the env in
389
+ // here once `hc run --env` lands (`awaitAdvisorCycle` already takes the file).
390
+ return { tabId, address, paneId: "", created: true };
391
+ }
392
+
393
+ /** Spawn the child in a new pane of an EXISTING tab (parallel same-type). */
394
+ async function spawnInSplitPane(opts: {
395
+ exec: HerdrExec;
396
+ tabId: string;
397
+ /** Anchor pane of that tab (from the caller's already-fetched listing). */
398
+ anchorPane: string;
399
+ cwd: string;
400
+ piArgs: string[];
401
+ direction: "right" | "down";
402
+ }): Promise<{ address: string; paneId: string }> {
403
+ const anchorPane = opts.anchorPane;
404
+ if (!anchorPane) throw new Error(`herdr-app: no panes found in tab ${opts.tabId}`);
405
+ const split = await appDo(opts.exec, "pane.split", {
406
+ direction: opts.direction,
407
+ pane: anchorPane,
408
+ argv: opts.piArgs,
409
+ });
410
+ if (!split.ok) throw new Error(`herdr-app pane.split failed: ${split.error}`);
411
+ const paneId = split.data?.pane;
412
+ const address = split.data?.terminal;
413
+ if (!address) throw new Error("herdr-app pane.split: unexpected response shape (missing terminal)");
414
+ return { address, paneId: paneId ?? "" };
415
+ }
416
+
417
+ // ponytail: per-agent-type serialization, herdr.ts prepareChains precedent —
418
+ // concurrent same-type dispatch would race tab create / name allocation; the
419
+ // expensive part (prompt + run) stays parallel.
420
+ const prepareChains = new Map<string, Promise<HerdrAppHandle>>();
421
+
422
+ async function prepareHerdrAppTaskUncached(opts: PrepareHerdrAppTaskOptions): Promise<HerdrAppHandle> {
423
+ const exec = herdrAppCli.exec;
424
+ if (Buffer.byteLength(opts.task, "utf8") > HERDR_TASK_BUDGET) {
425
+ throw new Error(`herdr-app task exceeds the ${HERDR_TASK_BUDGET}-byte budget (delivery wrapper included) — shorten the task or use runner:"sdk".`);
426
+ }
427
+ const liveIds = await liveTerminalIds(exec);
428
+ const name = allocateName(opts.agentType, [...liveIds, ...registry.keys()]);
429
+ const stamp = dispatchStamp();
430
+ const handle: HerdrAppHandle = {
431
+ tabName: opts.agentType,
432
+ tabId: "",
433
+ address: "",
434
+ paneId: "",
435
+ name,
436
+ agentType: opts.agentType,
437
+ task: opts.task,
438
+ resultFile: resultFilePath(opts.cwd, name, stamp),
439
+ advisorMarker: advisorMarkerPath(opts.cwd, stamp),
440
+ readOnly: opts.readOnly,
441
+ model: opts.model ?? "",
442
+ thinking: opts.thinking,
443
+ timeoutMs: opts.timeoutMs,
444
+ tabCreatedHere: true,
445
+ };
446
+ registry.set(handle.name, handle);
447
+ try {
448
+ await fs.mkdir(path.dirname(handle.resultFile), { recursive: true });
449
+ const systemPromptFile = path.join(path.dirname(handle.resultFile), `${name}.system.md`);
450
+ await fs.writeFile(systemPromptFile, opts.systemPrompt, "utf8");
451
+ // Build argv BEFORE topology so arg validation failures (read-only sandbox
452
+ // with no allowed tools) leave no orphan tab behind.
453
+ const piArgs = buildAppPiArgs({
454
+ name,
455
+ systemPromptFile,
456
+ model: opts.model,
457
+ thinking: opts.thinking,
458
+ tools: opts.tools,
459
+ readOnly: opts.readOnly,
460
+ sessionStamp: stamp,
461
+ });
462
+ const found = await resolveSpaceAndTab(exec, opts.agentType);
463
+ const existing = found.tab;
464
+ if (existing && existing.terminals.length > 0) {
465
+ // Adopt: same agent type already has a tab (this session or a previous
466
+ // one). Never ours to close; add a pane beside the existing work.
467
+ const direction = existing.terminals.length % 2 === 1 ? "right" : "down";
468
+ const split = await spawnInSplitPane({
469
+ exec,
470
+ tabId: existing.id,
471
+ anchorPane: existing.terminals[existing.terminals.length - 1]!.pane,
472
+ cwd: opts.cwd,
473
+ piArgs,
474
+ direction,
475
+ });
476
+ handle.tabId = existing.id;
477
+ handle.tabCreatedHere = false;
478
+ handle.address = split.address;
479
+ handle.paneId = split.paneId;
480
+ } else {
481
+ const space = found.space;
482
+ if (!space) {
483
+ throw new Error("herdr-app: no window/space is open — open the Herdr app (or use runner:\"sdk\").");
484
+ }
485
+ const spawned = await spawnInNewTab({
486
+ exec,
487
+ agentType: opts.agentType,
488
+ spaceId: space.id,
489
+ cwd: opts.cwd,
490
+ piArgs,
491
+ advisorMarker: handle.advisorMarker,
492
+ });
493
+ handle.tabId = spawned.tabId;
494
+ handle.address = spawned.address;
495
+ handle.paneId = spawned.paneId;
496
+ }
497
+ return handle;
498
+ } catch (err) {
499
+ registry.delete(handle.name);
500
+ throw err;
501
+ }
502
+ }
503
+
504
+ export function prepareHerdrAppTask(opts: PrepareHerdrAppTaskOptions): Promise<HerdrAppHandle> {
505
+ const prev = prepareChains.get(opts.agentType) ?? Promise.resolve(null as unknown as HerdrAppHandle);
506
+ const job = prev.then(
507
+ () => prepareHerdrAppTaskUncached(opts),
508
+ () => prepareHerdrAppTaskUncached(opts),
509
+ );
510
+ prepareChains.set(opts.agentType, job);
511
+ job.catch(() => { /* stored chain must not reject unhandled */ });
512
+ return job;
513
+ }
514
+
515
+ // ---------------------------------------------------------------------------
516
+ // Prompt + wait
517
+ // ---------------------------------------------------------------------------
518
+
519
+ /** Task + delivery contract (identical wording to the TUI backend). */
520
+ export function wrapAppTaskPrompt(task: string, resultFile: string, readOnly = false): string {
521
+ if (readOnly) {
522
+ return (
523
+ `${task}\n\n---\n` +
524
+ `Delivery: this session has read-only tools — do NOT write any files. ` +
525
+ `Reply with your full final report as your final message.`
526
+ );
527
+ }
528
+ return (
529
+ `${task}\n\n---\n` +
530
+ `Delivery: when your task is complete, write your full final report as Markdown to \`${resultFile}\` ` +
531
+ `(create parent directories if needed), then reply with a one-line summary only. ` +
532
+ `If follow-up feedback arrives after delivery (e.g. an advisor review), apply it and update the report file to the corrected version.`
533
+ );
534
+ }
535
+
536
+ /**
537
+ * Submit the task and wait for that turn to settle.
538
+ *
539
+ * `hc send --wait` follows the turn the send started (herdr-core tracks 7501
540
+ * turns), so no baseline/evidence machinery is needed — the TUI backend's
541
+ * stall workaround exists only because herdr 0.9.x never reports `working`
542
+ * for pi panes.
543
+ */
544
+ export async function promptAppAndWait(opts: {
545
+ address: string;
546
+ text: string;
547
+ timeoutMs: number;
548
+ exec: HerdrExec;
549
+ signal?: AbortSignal;
550
+ }): Promise<PromptOutcome> {
551
+ if (opts.signal?.aborted) {
552
+ return { state: "unknown", delivered: false, error: "aborted: parent operation aborted" };
553
+ }
554
+ // Readiness gate. `hc send` pastes into whatever is on screen; against a pi
555
+ // that is still booting the paste can land before the composer is live and
556
+ // the submit never registers (live incident 2026-11-17: the task sat unsent
557
+ // in the child's composer, `hc send --wait` still reported a settled turn,
558
+ // and the parent collected its own echoed task as "success"). The TUI backend
559
+ // gets this for free — `herdr agent start` waits for readiness — so the app
560
+ // path must wait explicitly (the hc manual's own advice).
561
+ const ready = await waitForReady(opts.address, opts.exec, opts.signal);
562
+ if (!ready.ok) {
563
+ return { state: ready.state, delivered: false, error: ready.error };
564
+ }
565
+ const baselineTurn = ready.turn;
566
+ const seconds = Math.max(5, Math.ceil(opts.timeoutMs / 1000));
567
+ const res = await opts.exec(
568
+ HC_BIN,
569
+ ["send", opts.address, opts.text, "--wait", "--timeout", String(seconds), "--json"],
570
+ { timeout: opts.timeoutMs + 20_000 },
571
+ );
572
+ // hc writes errors as JSON on STDERR; a failed call's stdout is not a reply.
573
+ const data = parseJson((res.code === 0 ? res.stdout : res.stderr).trim() || res.stdout.trim());
574
+ const errKind = data?.error?.kind;
575
+ if (res.code !== 0) {
576
+ if (errKind === "blocked") {
577
+ return { state: "blocked", delivered: false, error: "Agent is blocked on a dialog — answer it in its pane, then prompt again." };
578
+ }
579
+ if (errKind === "not_found") {
580
+ return { state: "unknown", delivered: false, error: data?.error?.message ?? "terminal not found" };
581
+ }
582
+ if (errKind === "status_mismatch" || errKind === "finished") {
583
+ return { state: "unknown", delivered: false, error: data?.error?.message ?? `send refused (${errKind})` };
584
+ }
585
+ return { state: "unknown", delivered: false, error: data?.error?.message ?? firstLine(res) };
586
+ }
587
+ const wait = data?.wait;
588
+ if (wait?.reason === "timeout") {
589
+ return {
590
+ state: await settledState(opts.address, opts.exec),
591
+ delivered: true,
592
+ error: `timeout after ${opts.timeoutMs}ms`,
593
+ };
594
+ }
595
+ const status = wait?.status;
596
+ const state: HerdrAgentState =
597
+ status === "idle" || status === "done" || status === "blocked" || status === "working"
598
+ ? status
599
+ : await settledState(opts.address, opts.exec);
600
+ if (data?.started === false || wait?.reason === "not_started") {
601
+ return { state, delivered: false, error: "the agent did not start working on the task (it may be waiting for input)" };
602
+ }
603
+ // Turn-advance proof: the child only advances its turn when it actually
604
+ // works. A "settled" reply with an unchanged turn means the paste never
605
+ // submitted — report that instead of collecting the echoed task as success.
606
+ const turnAfter = typeof wait?.turn === "number" ? wait.turn : undefined;
607
+ if (turnAfter !== undefined && turnAfter <= baselineTurn) {
608
+ return {
609
+ state,
610
+ delivered: false,
611
+ error: `the task was pasted but never submitted (turn still ${turnAfter}) — the child was not ready or a dialog holds the composer; prompt it again in its pane`,
612
+ };
613
+ }
614
+ return { state, delivered: true };
615
+ }
616
+
617
+ /** Poll until the terminal reports as a READY pi (idle, status-reporting). */
618
+ async function waitForReady(
619
+ address: string,
620
+ exec: HerdrExec,
621
+ signal?: AbortSignal,
622
+ ): Promise<{ ok: true; state: HerdrAgentState; turn: number } | { ok: false; state: HerdrAgentState; error: string }> {
623
+ const deadline = Date.now() + READY_TIMEOUT_MS;
624
+ let last: HerdrAppTerminal | undefined;
625
+ for (;;) {
626
+ if (signal?.aborted) return { ok: false, state: "unknown", error: "aborted: parent operation aborted" };
627
+ const got = await hcJson(exec, ["get", address], 10_000);
628
+ if (got.ok) {
629
+ const t = got.data?.result ?? got.data;
630
+ const raw = t?.status?.state;
631
+ const status: HerdrAgentState =
632
+ raw === "idle" || raw === "done" || raw === "blocked" || raw === "working" ? raw : "unknown";
633
+ last = {
634
+ address: t?.address ?? address,
635
+ status,
636
+ app: t?.status?.app ?? null,
637
+ state: t?.state === "live" || t?.state === "finished" ? t.state : "unknown",
638
+ };
639
+ if (last.state === "finished") {
640
+ return { ok: false, state: "unknown", error: "the child terminal exited before its task was sent" };
641
+ }
642
+ // Ready for input: a live pi at rest. `done` counts — pi reports "done"
643
+ // for a turn that finished while nobody was watching, and that composer
644
+ // accepts input exactly like `idle` (live 2026-11-17: accepting only
645
+ // `idle` made every follow-up prompt to an already-settled agent fail
646
+ // the readiness gate and time out). `working`/`blocked` are NOT ready.
647
+ if (t?.status?.app === "pi" && (status === "idle" || status === "done")) {
648
+ return { ok: true, state: status, turn: typeof t?.turn === "number" ? t.turn : 0 };
649
+ }
650
+ }
651
+ if (Date.now() >= deadline) {
652
+ return {
653
+ ok: false,
654
+ state: last?.status ?? "unknown",
655
+ error: `the child did not become ready for input within ${Math.round(READY_TIMEOUT_MS / 1000)}s${last?.status ? ` (last state: ${last.status})` : ""} — check its pane`,
656
+ };
657
+ }
658
+ await new Promise((resolve) => setTimeout(resolve, 700));
659
+ }
660
+ }
661
+
662
+ async function settledState(address: string, exec: HerdrExec): Promise<HerdrAgentState> {
663
+ const info = await getTerminal(address, exec);
664
+ return info?.status ?? "unknown";
665
+ }
666
+
667
+ // ---------------------------------------------------------------------------
668
+ // Collection & cancel
669
+ // ---------------------------------------------------------------------------
670
+
671
+ /** Report file first (delivery contract), pane tail as best-effort fallback. */
672
+ export async function collectAppResult(opts: {
673
+ handle: HerdrAppHandle;
674
+ exec: HerdrExec;
675
+ }): Promise<{ output: string; source: "file" | "pane" | "none" }> {
676
+ const fromFile = await readReportFile(opts.handle.resultFile);
677
+ if (fromFile) return { output: fromFile, source: "file" };
678
+ const read = await opts.exec(HC_BIN, ["read", opts.handle.address, "--lines", "200"], { timeout: 15_000 });
679
+ const paneText = read.code === 0 ? read.stdout.trim() : "";
680
+ if (!paneText) return { output: "", source: "none" };
681
+ // A pane holding only our own task echo (plus pi's startup chrome) is NOT a
682
+ // reply — that is the paste-never-submitted failure. Report no output so the
683
+ // caller fails loudly instead of returning the echo as a successful report.
684
+ const reply = replyBeyondEcho(paneText, opts.handle.task);
685
+ // A pane holding only our task echo (plus pi's chrome) is NOT a reply — the
686
+ // paste-never-submitted failure. Fail loudly instead of returning the echo.
687
+ if (!reply) return { output: "", source: "none" };
688
+ return { output: capPaneCapture(reply), source: "pane" };
689
+ }
690
+
691
+ /**
692
+ * The pane's reply, or "" when the pane holds nothing but our echoed task
693
+ * (the TUI backend's F10 rule: a settled echo is not a reply).
694
+ *
695
+ * Strategy — the reply is always AFTER our own text, so cut rather than
696
+ * subtract: find where our task + delivery contract ends and keep the tail.
697
+ * Everything before that point is boot chrome, resource lists and the paste
698
+ * itself, and the composer/status footer is dropped from the end. Subtracting
699
+ * known noise patterns instead kept leaking list continuations into the
700
+ * answer and, once tightened, ate the reply itself (live 2026-11-17).
701
+ */
702
+ function replyBeyondEcho(paneText: string, task: string): string {
703
+ // The composer line marks the end of the transcript region.
704
+ const lines = paneText.split("\n");
705
+ let end = lines.length;
706
+ for (let i = 0; i < lines.length; i++) {
707
+ if (/^\s*[\u03c0]\s*>/.test(lines[i]!)) { end = i; break; }
708
+ }
709
+ const region = lines.slice(0, end);
710
+
711
+ // The task + contract together are the last thing WE insert. Locate the
712
+ // first line of the task text (whitespace-tolerant, the TUI wraps it) and
713
+ // the end of the delivery contract that follows it.
714
+ const norm = (s: string) => s.replace(/\s+/g, " ").trim();
715
+ const flat = region.join("\n");
716
+ const flatNorm = norm(flat);
717
+
718
+ const contractEnd = (() => {
719
+ const re = /Delivery: [\s\S]*?(?:corrected version\.|final message\.)/g;
720
+ let last = -1;
721
+ for (const m of flatNorm.matchAll(re)) last = (m.index ?? 0) + m[0].length;
722
+ return last;
723
+ })();
724
+ if (contractEnd < 0) return ""; // no contract seen → not a dispatched turn
725
+
726
+ // Everything after the contract in the flattened capture is ours to read,
727
+ // minus hc's closing wrapper tag.
728
+ const tail = flatNorm
729
+ .slice(contractEnd)
730
+ .replace(/<\/?hc[^>]*>/g, " ")
731
+ // Status/footer chatter that follows the answer on the same capture.
732
+ .replace(/\u2191[\d.]+K?\s*\u2193[\d.]+[\s\S]*$/g, "")
733
+ .replace(/[\u03c0]\s*>.*$/g, "") // composer (if it survived flattening)
734
+ .trim();
735
+ if (tail) return tail;
736
+
737
+ // No contract (e.g. a follow-up the user typed): fall back to the text after
738
+ // the task echo, ignoring pure-chrome lines.
739
+ const at = task ? flatNorm.indexOf(norm(task)) : -1;
740
+ if (at < 0) return "";
741
+ return flatNorm.slice(at + norm(task).length).replace(/<\/?hc[^>]*>/g, " ").trim();
742
+ }
743
+
744
+ /**
745
+ * Interrupt a delegated agent. herdr-core's `interrupt` presses the program's
746
+ * own stop key (esc for an OSC-reporting program, else ctrl+c) and never
747
+ * escalates — so a still-working terminal additionally gets `kill`, the app
748
+ * equivalent of the TUI backend's esc→ctrl+c escalation.
749
+ */
750
+ export async function cancelAppAgent(address: string, exec: HerdrExec = herdrAppCli.exec): Promise<void> {
751
+ const res = await exec(HC_BIN, ["interrupt", address, "--json"], { timeout: 20_000 });
752
+ if (res.code !== 0) return;
753
+ const data = parseJson(res.stdout.trim());
754
+ const stillWorking = data?.status === "working" || data?.working === true;
755
+ if (!stillWorking) return;
756
+ try {
757
+ const info = await getTerminal(address, exec);
758
+ if (!isSettled(info)) await exec(HC_BIN, ["kill", address, "--json"], { timeout: 20_000 });
759
+ } catch { /* best effort */ }
760
+ }
761
+
762
+ // ---------------------------------------------------------------------------
763
+ // High-level flow
764
+ // ---------------------------------------------------------------------------
765
+
766
+ export interface ExecuteHerdrAppTaskOptions {
767
+ exec?: HerdrExec;
768
+ onState?: (state: string) => void;
769
+ signal?: AbortSignal;
770
+ advisorWaitMs?: number;
771
+ onAdvisorPhase?: (phase: string) => void;
772
+ }
773
+
774
+ /** Prompt the prepared agent, wait for settle, collect the report. */
775
+ export async function executeHerdrAppTask(
776
+ handle: HerdrAppHandle,
777
+ opts: ExecuteHerdrAppTaskOptions = {},
778
+ ): Promise<SubAgentResult> {
779
+ const exec = opts.exec ?? herdrAppCli.exec;
780
+ const startedAt = Date.now();
781
+ let pollTimer: ReturnType<typeof setInterval> | undefined;
782
+ let lastState = "";
783
+ let pollInFlight = false;
784
+ const poll = async () => {
785
+ if (pollInFlight) return;
786
+ pollInFlight = true;
787
+ try {
788
+ const state = await settledState(handle.address, exec);
789
+ if (state !== lastState) {
790
+ lastState = state;
791
+ opts.onState?.(state);
792
+ }
793
+ } catch { /* state poll is best-effort */ }
794
+ pollInFlight = false;
795
+ };
796
+ try {
797
+ pollTimer = setInterval(() => { void poll(); }, 2_000);
798
+ pollTimer.unref?.();
799
+ const prompt = await promptAppAndWait({
800
+ address: handle.address,
801
+ text: wrapAppTaskPrompt(handle.task, handle.resultFile, handle.readOnly),
802
+ timeoutMs: handle.timeoutMs,
803
+ exec,
804
+ signal: opts.signal,
805
+ });
806
+ let output = "";
807
+ let outputSource: "file" | "pane" | "none" = "none";
808
+ let advisorRounds = 0;
809
+ const aborted = Boolean(opts.signal?.aborted);
810
+ const timedOut = !aborted && Boolean(prompt.error && /timeout/.test(prompt.error));
811
+ if (timedOut) {
812
+ await cancelAppAgent(handle.address, exec);
813
+ prompt.error = `${prompt.error} (pane interrupted; it may still complete its current write — check ${path.basename(handle.resultFile)} or the pane before re-dispatching)`;
814
+ } else if (!aborted) {
815
+ advisorRounds = await awaitAdvisorCycle({
816
+ name: handle.address,
817
+ markerFile: handle.advisorMarker,
818
+ advisorWaitMs: opts.advisorWaitMs ?? 0,
819
+ signal: opts.signal,
820
+ onPhase: opts.onAdvisorPhase,
821
+ getState: () => settledState(handle.address, exec),
822
+ });
823
+ const collected = await collectAppResult({ handle, exec });
824
+ output = collected.output;
825
+ outputSource = collected.source;
826
+ }
827
+ const result = buildHerdrResult(
828
+ {
829
+ name: handle.name,
830
+ agentType: handle.agentType,
831
+ tabId: handle.tabId,
832
+ paneId: handle.paneId,
833
+ resultFile: handle.resultFile,
834
+ advisorMarker: handle.advisorMarker,
835
+ task: handle.task,
836
+ readOnly: handle.readOnly,
837
+ model: handle.model,
838
+ thinking: handle.thinking,
839
+ timeoutMs: handle.timeoutMs,
840
+ tabCreatedHere: handle.tabCreatedHere,
841
+ },
842
+ {
843
+ state: prompt.state,
844
+ delivered: prompt.delivered,
845
+ error: prompt.error,
846
+ output,
847
+ outputSource,
848
+ durationMs: Date.now() - startedAt,
849
+ },
850
+ );
851
+ if (advisorRounds > 0) result.advisorRounds = advisorRounds;
852
+ if (aborted) {
853
+ result.stopReason = "aborted";
854
+ result.status = "aborted";
855
+ result.exitCode = 1;
856
+ result.errorMessage = "Cancelled: parent operation aborted";
857
+ }
858
+ return result;
859
+ } finally {
860
+ if (pollTimer) clearInterval(pollTimer);
861
+ }
862
+ }
863
+
864
+ // ---------------------------------------------------------------------------
865
+ // Layout helpers for the control tool
866
+ // ---------------------------------------------------------------------------
867
+
868
+ /** Busy siblings in a tab (closing a tab kills every pane in it). */
869
+ export async function appTabCloseBlockers(
870
+ handle: HerdrAppHandle,
871
+ exec: HerdrExec,
872
+ ): Promise<{ siblings: string[]; self: string | undefined }> {
873
+ const siblings: string[] = [];
874
+ for (const entry of registry.values()) {
875
+ if (entry.tabId !== handle.tabId || entry.address === handle.address) continue;
876
+ const info = await getTerminal(entry.address, exec);
877
+ // Fail closed: only an observed settled state proves the sibling is free.
878
+ if (!isSettled(info)) siblings.push(entry.name);
879
+ }
880
+ const selfInfo = await getTerminal(handle.address, exec);
881
+ const self = selfInfo && !isSettled(selfInfo) ? selfInfo.status ?? "unknown" : undefined;
882
+ return { siblings, self };
883
+ }
884
+
885
+ /** Raise the agent's tab in the app window. */
886
+ export async function focusAppTab(tabId: string, exec: HerdrExec): Promise<{ ok: boolean; error?: string }> {
887
+ const res = await appDo(exec, "tab.select", { id: tabId }, 15_000);
888
+ return res.ok ? { ok: true } : { ok: false, error: res.error };
889
+ }
890
+
891
+ /** Close a tab this session created (and the terminals in it). */
892
+ export async function closeAppTab(tabId: string, exec: HerdrExec): Promise<{ ok: boolean; error?: string }> {
893
+ const res = await appDo(exec, "tab.close", { id: tabId, confirmed: true }, 30_000);
894
+ return res.ok ? { ok: true } : { ok: false, error: res.error };
895
+ }
896
+
897
+ /** Best-effort pane/screen text for one terminal. */
898
+ export async function readAppTerminal(
899
+ address: string,
900
+ lines: number,
901
+ exec: HerdrExec,
902
+ ): Promise<{ ok: boolean; text: string }> {
903
+ const clamped = Math.min(Math.max(Math.trunc(lines), 1), 1000);
904
+ const res = await exec(HC_BIN, ["read", address, "--lines", String(clamped)], { timeout: 15_000 });
905
+ return {
906
+ ok: res.code === 0,
907
+ text: res.code === 0 ? res.stdout.slice(0, MAX_REPORT_BYTES) : firstLine(res),
908
+ };
909
+ }
910
+
911
+ /** Submit a follow-up prompt without waiting (control tool, wait:false). */
912
+ export async function sendAppPrompt(address: string, text: string, exec: HerdrExec): Promise<{ ok: boolean; error?: string }> {
913
+ const res = await exec(HC_BIN, ["send", address, text, "--json"], { timeout: 20_000 });
914
+ if (res.code === 0) return { ok: true };
915
+ const data = parseJson(res.stderr.trim() || res.stdout.trim());
916
+ return { ok: false, error: data?.error?.message ?? firstLine(res) };
917
+ }