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.
@@ -298,10 +298,14 @@ export function clearHerdrRegistry(): void {
298
298
  // ---------------------------------------------------------------------------
299
299
 
300
300
  /** herdr injects HERDR_ENV=1 + workspace/pane IDs into every managed pane. */
301
- export function herdrEnvDetected(): boolean {
301
+ export function herdrTuiEnvDetected(): boolean {
302
302
  return process.env.HERDR_ENV === "1" && Boolean(process.env.HERDR_WORKSPACE_ID);
303
303
  }
304
304
 
305
+ /** Alias kept for the herdr-TUI call sites; herdr-APP detection lives in
306
+ * lib/herdr-app.ts (HC_TERMINAL_ID, set by herdr-core in every terminal). */
307
+ export const herdrEnvDetected = herdrTuiEnvDetected;
308
+
305
309
  /** settings.subagent.herdr === "off" (or the child recursion guard) disables herdr dispatch. */
306
310
  export function herdrDisabled(subagentSettings: { herdr?: unknown } | undefined): boolean {
307
311
  if (subagentSettings?.herdr === "off") return true;
@@ -749,15 +753,16 @@ export async function promptAndWait(opts: {
749
753
  /** Best-effort output collection: report file first, pane scrollback fallback. */
750
754
  /** Cap for report-file content fed back into the parent context. */
751
755
  export const MAX_REPORT_BYTES = 256 * 1024;
752
-
753
- export async function collectResult(opts: {
754
- handle: HerdrHandle;
755
- exec: HerdrExec;
756
- }): Promise<{ output: string; source: "file" | "pane" | "none" }> {
756
+ /** Cap for the pane-scrollback fallback (also bounds {previous} in chains). */
757
+ export const MAX_PANE_CAPTURE_BYTES = 8 * 1024;
758
+
759
+ /** The delivery-contract report file, or undefined when absent/empty.
760
+ * Shared by both backends (herdr TUI + herdr-app): open + stat FIRST, read at
761
+ * most MAX_REPORT_BYTES (+1 sentinel) — a runaway report (GBs) must not
762
+ * buffer whole into memory before the cap. */
763
+ export async function readReportFile(resultFile: string): Promise<string | undefined> {
757
764
  try {
758
- // F16: open + stat FIRST, read at most MAX_REPORT_BYTES (+1 sentinel) —
759
- // a runaway report (GBs) must not buffer whole into memory before the cap.
760
- const fh = await fs.open(opts.handle.resultFile, "r");
765
+ const fh = await fs.open(resultFile, "r");
761
766
  const want = Math.min((await fh.stat()).size, MAX_REPORT_BYTES + 1);
762
767
  const raw = Buffer.alloc(want);
763
768
  await fh.read(raw, 0, want, 0);
@@ -765,22 +770,32 @@ export async function collectResult(opts: {
765
770
  const text = raw.length > MAX_REPORT_BYTES
766
771
  ? raw.subarray(0, MAX_REPORT_BYTES).toString("utf8") + "\n\n…(truncated)"
767
772
  : raw.toString("utf8");
768
- if (text.trim()) return { output: text.trim(), source: "file" };
769
- } catch { /* no report file — fall back to pane read */ }
773
+ return text.trim() ? text.trim() : undefined;
774
+ } catch {
775
+ return undefined; // no report file — caller falls back to a pane read
776
+ }
777
+ }
778
+
779
+ /** Tail-cap pane capture text for parent context. */
780
+ export function capPaneCapture(paneText: string): string {
781
+ return paneText.length > MAX_PANE_CAPTURE_BYTES
782
+ ? "…(earlier pane output truncated)\n" + paneText.slice(-MAX_PANE_CAPTURE_BYTES)
783
+ : paneText;
784
+ }
785
+
786
+ export async function collectResult(opts: {
787
+ handle: HerdrHandle;
788
+ exec: HerdrExec;
789
+ }): Promise<{ output: string; source: "file" | "pane" | "none" }> {
790
+ const fromFile = await readReportFile(opts.handle.resultFile);
791
+ if (fromFile) return { output: fromFile, source: "file" };
770
792
  const read = await opts.exec(
771
793
  "herdr",
772
794
  ["agent", "read", opts.handle.name, "--source", "recent-unwrapped", "--lines", "200"],
773
795
  { timeout: 10_000 },
774
796
  );
775
797
  const paneText = read.code === 0 ? read.stdout.trim() : "";
776
- // Pane scrollback can contain pre-prompt noise (resumed sessions, earlier
777
- // turns). The final reply sits at the END, so cap to the tail — this also
778
- // bounds {previous} substitution in chains.
779
- const MAX_PANE_CAPTURE_BYTES = 8 * 1024;
780
- const capped = paneText.length > MAX_PANE_CAPTURE_BYTES
781
- ? "…(earlier pane output truncated)\n" + paneText.slice(-MAX_PANE_CAPTURE_BYTES)
782
- : paneText;
783
- return { output: capped, source: paneText ? "pane" : "none" };
798
+ return { output: capPaneCapture(paneText), source: paneText ? "pane" : "none" };
784
799
  }
785
800
 
786
801
  /** Interrupt a delegated agent: esc first (pi interrupt), ctrl+c if still working. */
@@ -847,12 +862,12 @@ export function buildHerdrResult(
847
862
  status = "success";
848
863
  }
849
864
  // Synthetic assistant message carrying the report — keeps getResultOutput /
850
- // renderSingleResult working unchanged (they read result.messages).
851
- // Pane-source output is a best-effort capture (echoed task, TUI noise) —
852
- // label it so the parent treats it with appropriate distrust.
853
- const output = outcome.outputSource === "pane" && outcome.output
854
- ? `[best-effort pane capture]\n\n${outcome.output}`
855
- : outcome.output;
865
+ // renderSingleResult working unchanged (they read result.messages). Pane
866
+ // output is best-effort (echoed task, TUI noise); that is flagged as the
867
+ // `bestEffort` DATA field below, NOT as a text prefix: a prefix travelled
868
+ // into `{previous}` chain substitution and derailed the next step (live
869
+ // 2026-11-17: the child read the marker as a prompt-injection signal).
870
+ const output = outcome.output;
856
871
  const messages = (output
857
872
  ? [{ role: "assistant", content: [{ type: "text", text: output }], stopReason: "stop" }]
858
873
  : []) as unknown as Message[];
@@ -870,6 +885,7 @@ export function buildHerdrResult(
870
885
  errorMessage,
871
886
  status,
872
887
  durationMs: outcome.durationMs,
888
+ bestEffort: outcome.outputSource === "pane" && Boolean(output),
873
889
  };
874
890
  }
875
891
 
@@ -902,7 +918,7 @@ function advisorMarkerPath(cwd: string, stamp: string): string {
902
918
  }
903
919
 
904
920
  /** Session + report files share one stamp so they correlate per dispatch. */
905
- function dispatchStamp(): string {
921
+ export function dispatchStamp(): string {
906
922
  return Date.now().toString(36);
907
923
  }
908
924
 
@@ -1054,15 +1070,20 @@ function readAdvisorMarkerFile(file: string): AdvisorMarker | undefined {
1054
1070
  *
1055
1071
  * Returns the number of steered revisions folded in.
1056
1072
  */
1057
- async function awaitAdvisorCycle(opts: {
1073
+ export async function awaitAdvisorCycle(opts: {
1058
1074
  name: string;
1059
1075
  markerFile: string;
1060
1076
  advisorWaitMs: number;
1061
1077
  signal?: AbortSignal;
1062
1078
  onPhase?: (phase: string) => void;
1063
- exec: HerdrExec;
1079
+ /** pane-state probe; defaults to the herdr-TUI `agent get` reader. The
1080
+ * herdr-app backend passes its own `hc get` probe. */
1081
+ exec?: HerdrExec;
1082
+ getState?: () => Promise<HerdrAgentState>;
1064
1083
  }): Promise<number> {
1065
1084
  if (opts.advisorWaitMs <= 0) return 0;
1085
+ const probeState = opts.getState
1086
+ ?? (() => getAgentState(opts.name, opts.exec ?? defaultExec));
1066
1087
  const deadline = Date.now() + opts.advisorWaitMs;
1067
1088
  const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
1068
1089
  const stopped = () => Boolean(opts.signal?.aborted) || Date.now() >= deadline;
@@ -1093,7 +1114,7 @@ async function awaitAdvisorCycle(opts: {
1093
1114
  opts.onPhase?.("advisor-revise");
1094
1115
  let sawWorking = false;
1095
1116
  while (!stopped()) {
1096
- const state = await getAgentState(opts.name, opts.exec);
1117
+ const state = await probeState();
1097
1118
  if (state === "working" || state === "blocked") sawWorking = true;
1098
1119
  else if (sawWorking && (state === "idle" || state === "done")) break;
1099
1120
  await sleep(1000);
@@ -11,7 +11,8 @@ import * as os from "node:os";
11
11
  import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
12
12
  import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
13
13
  import type { Message } from "./types.ts";
14
- import { type SubAgentResult, isFailedResult, getResultOutput, getFinalOutput } from "./runner.ts";
14
+ import { type SubAgentResult, isFailedResult, getResultOutput, getFinalOutput, formatPatchBlock } from "./runner.ts";
15
+ import { truncateParallelOutput } from "./security.ts";
15
16
 
16
17
  // ---------------------------------------------------------------------------
17
18
  // Safe type guards
@@ -31,6 +32,21 @@ export function asRecord(value: unknown): Record<string, unknown> {
31
32
  : {};
32
33
  }
33
34
 
35
+ /**
36
+ * The configured key(s) that toggle tool output, for `(… to expand)` hints.
37
+ * pi 1.5.x hands every tool render context a `keyText`/`keyHint` pair that
38
+ * resolves the HOST's keybindings (`app.tools.expand`, ctrl+o by default), so
39
+ * a user rebind is reflected instead of a hardcoded "Ctrl+O". Contexts without
40
+ * it (pi <1.5, widget/thread renderers) keep the literal.
41
+ */
42
+ export function expandKeyLabel(context?: { keyText?: (k: "app.tools.expand") => string }): string {
43
+ try {
44
+ return context?.keyText?.("app.tools.expand") || "Ctrl+O";
45
+ } catch {
46
+ return "Ctrl+O";
47
+ }
48
+ }
49
+
34
50
  // ---------------------------------------------------------------------------
35
51
  // Display helpers
36
52
  // ---------------------------------------------------------------------------
@@ -52,6 +68,29 @@ function formatMs(ms: number): string {
52
68
  return `${ms}ms`;
53
69
  }
54
70
 
71
+ /**
72
+ * The chain result's text: the FINAL step's output first (what callers act on),
73
+ * then every step's report. `{previous}` only carries one step forward, so
74
+ * without the per-step section an intermediate step's findings vanish from the
75
+ * result entirely. Patches stay labeled per step for ordered merging.
76
+ */
77
+ export function formatChainReport(finalText: string, results: SubAgentResult[]): string {
78
+ const perStep = results
79
+ .map((r, i) => {
80
+ const status = isFailedResult(r)
81
+ ? `failed${r.stopReason ? ` (${r.stopReason})` : ""}`
82
+ : r.stopReason === "blocked"
83
+ ? "blocked — awaiting input in its pane"
84
+ : "completed";
85
+ const body = truncateParallelOutput(getResultOutput(r));
86
+ const patch = formatPatchBlock(r);
87
+ const caveat = r.bestEffort ? " ⚠ best-effort pane capture" : "";
88
+ return `### Step ${i + 1}/${results.length} — ${r.agent}: ${status}${caveat}\n\n${body}${patch ? `\n\n${patch}` : ""}`;
89
+ })
90
+ .join("\n\n---\n\n");
91
+ return [finalText || "(no output)", `---\n\n## Chain steps (${results.length})\n\n${perStep}`].join("\n\n");
92
+ }
93
+
55
94
  export function formatUsageStats(
56
95
  usage: { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number; contextTokens?: number; turns?: number },
57
96
  model?: string,
@@ -214,6 +253,8 @@ export function renderSingleResult(
214
253
  expanded: boolean,
215
254
  theme: { fg: (c: any, t: string) => string; bold: (t: string) => string },
216
255
  agentColor?: string,
256
+ /** Configured expand key label — see expandKeyLabel(). */
257
+ expandKey = "Ctrl+O",
217
258
  ): Container | Text {
218
259
  const isError = isFailedResult(result);
219
260
  const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
@@ -238,7 +279,11 @@ export function renderSingleResult(
238
279
  container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
239
280
  container.addChild(new Text(theme.fg("dim", result.task), 0, 0));
240
281
  container.addChild(new Spacer(1));
241
- container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
282
+ container.addChild(new Text(
283
+ theme.fg("muted", "─── Output ───") +
284
+ (result.bestEffort ? ` ${theme.fg("warning", "(best-effort pane capture)")}` : ""),
285
+ 0, 0,
286
+ ));
242
287
  if (displayItems.length === 0 && !finalOutput) {
243
288
  container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
244
289
  } else {
@@ -299,20 +344,23 @@ export function renderSingleResult(
299
344
  text += `\n${theme.fg("muted", "(no output)")}`;
300
345
  } else if (rawOutput.trim() !== "") {
301
346
  // All-structural output (headings/bullets/fences only) — still say so.
302
- text += `\n${theme.fg("dim", "⎿ (markdown answer — Ctrl+O to view)")}`;
347
+ text += `\n${theme.fg("dim", `⎿ (markdown answer — ${expandKey} to view)`)}`;
303
348
  }
304
349
  } else if (!result.errorMessage && rawOutput.trim() === "" && !result.stderr) {
305
350
  // Error with no message, no stderr, no assistant output — say so.
306
351
  // (When errorMessage IS set, the Error: line above already conveys it.)
307
352
  text += `\n${theme.fg("muted", "(no output)")}`;
308
353
  }
354
+ // Provenance of a scraped answer travels as DATA (result.bestEffort), never
355
+ // as a text prefix — a prefix would flow into `{previous}` chain payloads.
356
+ if (result.bestEffort) text += `\n${theme.fg("warning", "⚠ best-effort pane capture")}`;
309
357
  const usageStr = formatUsageStats(result.usage, result.model, { toolCount, durationMs: result.durationMs, thinking: result.thinking, advisorRounds: result.advisorRounds });
310
358
  if (usageStr) text += `\n${theme.fg("dim", usageStr)}`;
311
359
  if (result.patch) text += `\n${theme.fg("success", "🌿 worktree")} (${result.patch.split("\n").length} diff lines)`;
312
360
  // Hint: getResultOutput always returns at least "(no output)", so finalOutput
313
361
  // is always truthy — show the hint whenever there's any trace to expand.
314
362
  if (displayItems.length > 0 || (finalOutput && finalOutput !== "(no output)") || result.messages.length > 0) {
315
- text += `\n${theme.fg("muted", "(Ctrl+O to expand · /agent for full thread)")}`;
363
+ text += `\n${theme.fg("muted", `(${expandKey} to expand · /agent for full thread)`)}`;
316
364
  }
317
365
  return new Text(text, 0, 0);
318
366
  }
@@ -148,6 +148,11 @@ export interface SubAgentResult {
148
148
  status?: SubagentStatus;
149
149
  /** Wall-clock duration of the run, set by runSubAgent (Date.now() - startedAt). */
150
150
  durationMs?: number;
151
+ /** True when the output was scraped from a pane's scrollback rather than a
152
+ * report file or structured messages — the parent should treat it with
153
+ * appropriate distrust. Provenance DATA, not a prefix: pasting a marker
154
+ * into the text poisons `{previous}` chain substitution (live 2026-11-17). */
155
+ bestEffort?: boolean;
151
156
  }
152
157
 
153
158
  // ---------------------------------------------------------------------------