ceulen 0.26.0 → 0.26.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,77 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.26.2 — 2026-11-15
4
+
5
+ Pi 1.5.2 support (pi 1.5.0 → 1.5.2 diffed surface by surface; the peer
6
+ range `>=0.99.1 <1.6.0` from 0.26.0 already covered it, so no range change).
7
+ **No breaking changes for ceulen.** Everything below the fold is stock-parity
8
+ plus one deferred feature finally landed.
9
+
10
+ - **`/config` Cache warming row no longer warns on a pristine config.** Pi
11
+ 1.5.1 flipped the setting's default from `streaming` to `idle`; ceulen's
12
+ row still carried the old default and rendered warning-styled (the
13
+ pi.tuiMode-1.0.0 failure mode). `CACHE_WARMING`'s option list and the
14
+ setter are unchanged.
15
+ - **Subagent expand hints follow the user's keybinding.** The six
16
+ `(Ctrl+O to expand)` hints were hardcoded; they now read
17
+ `keyText("app.tools.expand")` from the render context (pi's
18
+ `KeybindingHints`, added in 1.5.0), so a rebind shows up. `expandKeyLabel()`
19
+ in `subagent/lib/render.ts` falls back to the literal `Ctrl+O` when the
20
+ context has no hints (the above-editor widget and `/agent` thread viewer
21
+ receive none) or a hint lookup throws — older pi keeps today's text.
22
+
23
+ Audited and left alone: tool argument validation (`prepareArguments` still
24
+ runs before `validateToolArguments` — repair's hook position is unchanged),
25
+ the new `MarkdownTransformerOptions` (ceulen registers no markdown
26
+ transformer), and `createReadStream` / the deprecated
27
+ `GrepOperations.readFile` (repair wraps read/grep by name through the host
28
+ factory with no custom `operations`, so 1.5.2's streaming read and
29
+ ripgrep-sourced context lines flow into the wrapped tools for free).
30
+ `settings-manager`, `settings-selector`, `theme-schema`, `jiti-loader`,
31
+ `trust-manager`, `custom-editor` and the root export map are byte-identical
32
+ across 1.5.0 → 1.5.2.
33
+
34
+ Verified: `tsc --noEmit` clean against 1.5.2 types; 2962 tests / 2959 pass /
35
+ 0 fail / 3 known env-gated skips (a2a mDNS, web a11y Chrome); live rpc smoke
36
+ on 1.5.2 registers all 60 commands, runs `/ceulen`, zero stderr.
37
+
38
+ ## 0.26.1 — 2026-11-04
39
+
40
+ **Fix: inbound A2A dispatches blanked the host TUI's status band (model ·
41
+ cwd · git · context) until restart.**
42
+
43
+ Root cause: each inbound dispatch runs a child pi session **in this
44
+ process** (`makeSessionRunner` → `bindExtensions({mode:"print"})` fires the
45
+ child's `session_start`; the dispose path emits `session_shutdown`). Pi
46
+ re-invokes ceulen's module factories for the child while ES-module scope
47
+ stays shared — so the child's lifecycle clobbered host module-scope state.
48
+ Worst hit: composer's `liveCtx` (child shutdown cleared it → the status
49
+ band renders blank; band shapes had replaced pi's native footer, so ALL
50
+ identity info vanished — the reported screenshot). Same family: the
51
+ child's shutdown cleared the classifier registry (host `classify`/
52
+ planGate/thinkGate stopped resolving), killed the host's background
53
+ subagent tasks and auto-bg bash jobs, stopped the shared serena worker,
54
+ reset the usage/rate band items, fed child turns into the host's tok/s +
55
+ cost totals, and re-armed cron's process timer + router's catalog interval
56
+ onto the disposed child.
57
+
58
+ Fix: `extensions/lib/child-session.ts` — a `markChildSession`
59
+ WeakSet (a2a's runner + subagent's extension-loading runner mark their
60
+ child session managers) + `beginChildFactory()/endChildFactory()` depth
61
+ window around the loaders' `reload()`. Handlers that write module-scope or
62
+ process-wide state gate on `isChildSession(ctx.sessionManager)`; factory-
63
+ time arms (cron's interval, router's catalog refresh) gate on
64
+ `childFactoryDepth()`. Gated modules: composer, classifier, usage,
65
+ subagent, cron, serena, router, permission, repair. Children keep their
66
+ tools and per-turn handlers (steering, fff, repair arg-fixing) — only
67
+ host-owned bookkeeping is protected.
68
+
69
+ Verified: unit + integration tests (`child-session.test.ts`, a2a
70
+ `child-contamination.test.ts` — drives the real composer handlers), and a
71
+ live SDK probe (`scripts/child-session-probe.ts`) that creates a real
72
+ child session through the exact a2a runner path and asserts the host's
73
+ `liveCtx` survives the full child lifecycle. Full suite 2956/0 fail.
74
+
3
75
  ## 0.26.0 — 2026-11-03
4
76
 
5
77
  Pi 1.5.0 support (peer range was `<1.5.0`, which semver-excluded the new
@@ -0,0 +1,54 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import {
4
+ beginChildFactory,
5
+ childFactoryDepth,
6
+ endChildFactory,
7
+ isChildSession,
8
+ markChildSession,
9
+ } from "./child-session.ts";
10
+
11
+ test("unmarked sessions are not children (host events run)", () => {
12
+ const host = { id: "host" };
13
+ assert.equal(isChildSession(host), false);
14
+ // undefined/no-ctx callers (older hosts, tests) read as host too
15
+ assert.equal(isChildSession(undefined), false);
16
+ assert.equal(isChildSession(null), false);
17
+ });
18
+
19
+ test("marked session managers are children; other sessions are not", () => {
20
+ const child = { id: "child" };
21
+ const host = { id: "host" };
22
+ markChildSession(child);
23
+ assert.equal(isChildSession(child), true);
24
+ assert.equal(isChildSession(host), false);
25
+ });
26
+
27
+ test("factory depth window opens and closes, floors at zero", () => {
28
+ assert.equal(childFactoryDepth(), 0);
29
+ beginChildFactory();
30
+ beginChildFactory();
31
+ assert.equal(childFactoryDepth(), 2);
32
+ endChildFactory();
33
+ endChildFactory();
34
+ assert.equal(childFactoryDepth(), 0);
35
+ endChildFactory(); // stray end must never go negative
36
+ assert.equal(childFactoryDepth(), 0);
37
+ });
38
+
39
+ test("nested windows: inner finally does not close the outer window", () => {
40
+ assert.equal(childFactoryDepth(), 0);
41
+ beginChildFactory();
42
+ try {
43
+ beginChildFactory();
44
+ try {
45
+ assert.equal(childFactoryDepth(), 2);
46
+ } finally {
47
+ endChildFactory();
48
+ }
49
+ assert.equal(childFactoryDepth(), 1, "outer window still open");
50
+ } finally {
51
+ endChildFactory();
52
+ }
53
+ assert.equal(childFactoryDepth(), 0);
54
+ });
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Child-session identity — inbound A2A dispatches and extension-loading
3
+ * subagent children run child pi sessions IN THIS PROCESS. Pi re-invokes the
4
+ * ceulen factories for each child (during the child's resourceLoader.reload),
5
+ * but ES-module scope is shared by every factory invocation, so a child's
6
+ * session lifecycle must never write module-scope state. Live incident
7
+ * (2026-11): the first inbound dispatch blanked the host TUI's entire status
8
+ * band — the child's session_shutdown cleared composer's module-scope
9
+ * liveCtx, and the band shape had replaced pi's native footer, so model,
10
+ * cwd, git and context vanished until restart. Same family: the child's
11
+ * shutdown cleared the classifier registry (host classify/planGate died),
12
+ * killed the host's background subagent tasks, stopped the shared serena
13
+ * worker, reset the usage band stores, and re-armed cron's process timer
14
+ * onto a disposed child.
15
+ *
16
+ * Two primitives:
17
+ * - isChildSession(ctx.sessionManager): EVENT-time gate. Handlers that write
18
+ * module-scope state drop events from marked sessions. The child keeps
19
+ * everything registered at factory load plus its own per-turn handlers —
20
+ * only per-session bookkeeping of shared state is host-owned. pi -p and
21
+ * RPC hosts are never marked (no child is ever created inside them), so
22
+ * headless pi keeps working unchanged.
23
+ * - childFactoryDepth(): FACTORY-LOAD-time gate (cron's process timer,
24
+ * router's refresh interval). Factories run during child creation; the
25
+ * runners open the window around resourceLoader.reload() only.
26
+ */
27
+
28
+ const childSessionManagers = new WeakSet<object>();
29
+ let depth = 0;
30
+
31
+ /** Mark a session manager as belonging to an in-process child session. */
32
+ export function markChildSession(sm: unknown): void {
33
+ if (sm && typeof sm === "object") childSessionManagers.add(sm as object);
34
+ }
35
+
36
+ /** Whether this ctx belongs to an in-process child session (a2a inbound
37
+ * dispatch, subagent SDK child). */
38
+ export function isChildSession(sm: unknown): boolean {
39
+ return !!sm && typeof sm === "object" && childSessionManagers.has(sm as object);
40
+ }
41
+
42
+ /** Open a child-creation window: ceulen factories re-run inside it. Must be
43
+ * paired with endChildFactory() in a finally — a leaked depth would disarm
44
+ * the host's process timer for the rest of the process lifetime. */
45
+ export function beginChildFactory(): void {
46
+ depth += 1;
47
+ }
48
+
49
+ /** Close a child-creation window. Floors at 0: a stray end must never
50
+ * underflow into negative depth (which would read as "host" forever). */
51
+ export function endChildFactory(): void {
52
+ depth = Math.max(0, depth - 1);
53
+ }
54
+
55
+ /** Current child-creation depth. >0 while child factories/session_start run. */
56
+ export function childFactoryDepth(): number {
57
+ return depth;
58
+ }
@@ -31,6 +31,7 @@ import {
31
31
  metrics,
32
32
  } from "./lib/client";
33
33
  import { A2AServer, type SessionRunner } from "./lib/server";
34
+ import { beginChildFactory, endChildFactory, markChildSession } from "../../lib/child-session.js";
34
35
  import { formatPeers, listPeers } from "./lib/discovery";
35
36
  import { childTranscriptDir } from "./lib/persistence";
36
37
  import { activityLine, activityStatusLine, activityToText, classifyLine, dispatchLabel, preview, type InboundActivity } from "./lib/activity";
@@ -107,12 +108,19 @@ function makeSessionRunner(ctx: ExtensionContext, cfg?: A2AConfig): SessionRunne
107
108
  cwd,
108
109
  agentDir: sdk.getAgentDir(),
109
110
  });
110
- await resourceLoader.reload({
111
- // Forward the host's trust decision so project-local (.pi/) extensions
112
- // load in child sessions when the user already trusted the project —
113
- // same behavior as pi-subagent's runner; never prompt (no UI).
114
- resolveProjectTrust: async () => (ctx as any).isProjectTrusted?.() ?? false,
115
- });
111
+ // Child-creation window: ceulen factories re-run inside reload() —
112
+ // cron/router factory-load gates read this depth.
113
+ beginChildFactory();
114
+ try {
115
+ await resourceLoader.reload({
116
+ // Forward the host's trust decision so project-local (.pi/) extensions
117
+ // load in child sessions when the user already trusted the project —
118
+ // same behavior as pi-subagent's runner; never prompt (no UI).
119
+ resolveProjectTrust: async () => (ctx as any).isProjectTrusted?.() ?? false,
120
+ });
121
+ } finally {
122
+ endChildFactory();
123
+ }
116
124
  // Persist the child's transcript (fleet task #252). Stock pi-a2a ran
117
125
  // children on SessionManager.inMemory, so a dispatched worker that
118
126
  // stalled or was killed mid-run left NO step history — the only evidence
@@ -189,6 +197,14 @@ function makeSessionRunner(ctx: ExtensionContext, cfg?: A2AConfig): SessionRunne
189
197
  // session_start) are silently missing from dispatched sessions. mode
190
198
  // "print" with no uiContext keeps ctx.hasUI === false, matching how the
191
199
  // host-only session_start guard below classifies child sessions.
200
+ //
201
+ // markChildSession + the factory window: ceulen's factories re-run when
202
+ // the child's resource loader reloads, and the child's session_start /
203
+ // session_shutdown fire right here — both in THIS process, sharing
204
+ // ceulen's ES-module scope with the host. The mark + depth let ceulen's
205
+ // host-owned handlers drop the child's lifecycle events instead of
206
+ // clobbering host state (the blank-status-band incident).
207
+ markChildSession(sessionManager);
192
208
  try {
193
209
  await session.bindExtensions({ mode: "print" });
194
210
  } catch {
@@ -0,0 +1,80 @@
1
+ /** Regression tests for the in-process child-session contamination incident
2
+ * (2026-11): an inbound A2A dispatch (and any extension-loading subagent
3
+ * child) runs a child pi session in the HOST process. Pi re-invokes ceulen's
4
+ * factories for the child while ES-module scope stays shared, so a child's
5
+ * session_start / session_shutdown used to clobber host module-scope state —
6
+ * live symptom: the host TUI lost its whole status band (model · cwd · git ·
7
+ * context) after the first inbound dispatch, until restart.
8
+ *
9
+ * Drive the REAL module handlers with a host ctx, then fire the same
10
+ * handlers with a ctx whose sessionManager is marked as a child, and assert
11
+ * the host state survived. */
12
+ import { describe, it } from "node:test";
13
+ import { assert } from "./chai.js";
14
+ import { markChildSession } from "../../../lib/child-session.ts";
15
+ import composerModule, { __liveCtxForTests } from "../../composer/index.ts";
16
+
17
+ /** Fire-the-registered-handlers harness (module.test.ts pattern). */
18
+ function harness(factory: (pi: any) => void, opts: Record<string, unknown> = {}) {
19
+ const handlers = new Map<string, Array<(e: any, c: any) => any>>();
20
+ factory({
21
+ on: (event: string, handler: (e: any, c: any) => any) => {
22
+ handlers.set(event, [...(handlers.get(event) ?? []), handler]);
23
+ },
24
+ ...opts,
25
+ });
26
+ return {
27
+ fire: async (event: string, e: any, ctx: any) => {
28
+ for (const h of handlers.get(event) ?? []) await h(e, ctx);
29
+ },
30
+ };
31
+ }
32
+
33
+ function makeCtx(sessionManager: object, mode = "tui") {
34
+ const calls: string[] = [];
35
+ return {
36
+ calls,
37
+ mode,
38
+ hasUI: mode === "tui",
39
+ cwd: "/tmp/host",
40
+ sessionManager,
41
+ thinkingLevel: "medium",
42
+ ui: {
43
+ theme: { fg: (_c: string, s: string) => s, bold: (s: string) => s },
44
+ notify: () => {},
45
+ setStatus: () => {},
46
+ setWidget: () => {},
47
+ setEditorComponent: () => calls.push("setEditorComponent"),
48
+ setFooter: () => calls.push("setFooter"),
49
+ },
50
+ };
51
+ }
52
+
53
+ describe("child-session contamination: composer liveCtx", () => {
54
+ it("child session_start/shutdown never install or clear the host's liveCtx", async () => {
55
+ const host = harness(composerModule as any, { getSettings: () => ({ compaction: { enabled: true } }) });
56
+ const hostCtx = makeCtx({ id: "host" });
57
+ await host.fire("session_start", {}, hostCtx);
58
+ assert.equal(__liveCtxForTests(), hostCtx, "host session_start installed liveCtx");
59
+ assert.ok(hostCtx.calls.includes("setEditorComponent"), "host start applied the shape");
60
+
61
+ // Child lifecycle on the SAME module handlers (in-process child shares
62
+ // this module scope — that is the incident's mechanism).
63
+ const childCtx = makeCtx({ id: "child" }, "print");
64
+ markChildSession(childCtx.sessionManager);
65
+ await host.fire("session_start", {}, childCtx);
66
+ assert.equal(__liveCtxForTests(), hostCtx, "child session_start did NOT overwrite liveCtx");
67
+ assert.equal(
68
+ childCtx.calls.includes("setEditorComponent"),
69
+ false,
70
+ "child session_start did not re-wrap the host editor",
71
+ );
72
+
73
+ await host.fire("session_shutdown", {}, childCtx);
74
+ assert.notEqual(__liveCtxForTests(), undefined, "child session_shutdown did NOT clear liveCtx (the incident)");
75
+
76
+ // Host teardown still honored (guard does not over-block).
77
+ await host.fire("session_shutdown", {}, hostCtx);
78
+ assert.equal(__liveCtxForTests(), undefined, "host shutdown still clears");
79
+ });
80
+ });
@@ -34,6 +34,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
34
34
  import { getClassifierSettings } from "./lib/settings.js";
35
35
  import { registerThinkGate } from "./lib/think-gate.js";
36
36
  import { setClassifierRegistry } from "./configPanel.js";
37
+ import { isChildSession } from "../../lib/child-session.js";
37
38
 
38
39
  // ── Risk gate (static, before Jev ever sees a command) ──────────────────────
39
40
 
@@ -179,9 +180,14 @@ export default function (pi: ExtensionAPI) {
179
180
  // here (the panel always opens after a session exists). Cleared on shutdown
180
181
  // so a stale registry never survives session replacement (router's pattern).
181
182
  pi.on("session_start", (_event, ctx) => {
183
+ // Module-scope registry stash — host-owned (a2a/subagent children share
184
+ // this process's module scope; their shutdown must not clear the host's
185
+ // registry or the host's classify/planGate/thinkGate stop resolving).
186
+ if (isChildSession(ctx.sessionManager)) return;
182
187
  setClassifierRegistry(ctx.modelRegistry);
183
188
  });
184
- pi.on("session_shutdown", () => {
189
+ pi.on("session_shutdown", (_event, ctx) => {
190
+ if (isChildSession(ctx.sessionManager)) return;
185
191
  setClassifierRegistry(undefined);
186
192
  });
187
193
 
@@ -20,6 +20,7 @@ import type { ModuleConfig } from "../../lib/registry.js";
20
20
  import { row, type PanelGroup, type PanelMenuOption } from "../../lib/panel.js";
21
21
  import { getGenRate } from "../../lib/rate.js";
22
22
  import { USAGE_STATUS_KEY, getUsageItem } from "../../lib/usage-store.js";
23
+ import { isChildSession } from "../../lib/child-session.js";
23
24
  import { ComposerFooter, statsLine, sessionTotals } from "./lib/footer.ts";
24
25
  import { execFile } from "node:child_process";
25
26
  import { DEFAULT_SHAPE, IDENTITY_THEME, isShapeId, parseGitStats, previewShape, readGitBranch, ShapeEditor, shapeById, shapeTheme, SHAPES, type BandData, type GitStats, type ShapeTheme } from "./lib/shapes.ts";
@@ -28,6 +29,12 @@ import { readComposerShape, writeComposerSection } from "./lib/settings.ts";
28
29
  /** Live band/status data from the freshest session ctx; blank rather than stale. */
29
30
  let liveCtx: ExtensionContext | undefined;
30
31
 
32
+ /** Test probe: the current module-scope liveCtx (child-contamination
33
+ * regression tests). Undefined when no host session is installed. */
34
+ export function __liveCtxForTests(): ExtensionContext | undefined {
35
+ return liveCtx;
36
+ }
37
+
31
38
  /** Session-entry slice the footer totals read (structural; pi's entries fit). */
32
39
  interface FooterDataLike {
33
40
  getExtensionStatuses(): ReadonlyMap<string, string>;
@@ -281,15 +288,23 @@ export function composerConfig(_pi?: ExtensionAPI): ModuleConfig {
281
288
 
282
289
  export default function composerModule(pi: ExtensionAPI): void {
283
290
  pi.on("session_start", async (_event, ctx) => {
291
+ // liveCtx is MODULE-scope, shared with in-process child sessions (a2a
292
+ // inbound dispatches, extension-loading subagent children). A child's
293
+ // start/shutdown must never install or clear it — the child's shutdown
294
+ // blanked the host's whole status band (model · cwd · git · context)
295
+ // until restart, the reported bug.
296
+ if (isChildSession(ctx.sessionManager)) return;
284
297
  liveCtx = ctx;
285
298
  liveAutoCompact = readAutoCompact(pi);
286
299
  liveThinkingLevel = ctx.thinkingLevel;
287
300
  applyShape(readComposerShape(), ctx);
288
301
  });
289
- pi.on("thinking_level_select", async (event) => {
302
+ pi.on("thinking_level_select", async (event, ctx) => {
303
+ if (isChildSession(ctx.sessionManager)) return; // module-scope label — host-owned
290
304
  liveThinkingLevel = event.level;
291
305
  });
292
- pi.on("session_shutdown", async () => {
306
+ pi.on("session_shutdown", async (_event, ctx) => {
307
+ if (isChildSession(ctx.sessionManager)) return;
293
308
  liveCtx = undefined;
294
309
  });
295
310
  }
@@ -422,7 +422,7 @@ function piRowSpecs(m: SettingsManager, lookup?: PiMenuLookup): PiRowSpec[] {
422
422
  },
423
423
  {
424
424
  key: "pi.cacheWarming", tab: "Model", section: "Efficiency", label: "Cache warming",
425
- kind: "string", value: m.getCacheWarmingMode(), values: CACHE_WARMING, defaultValue: "streaming",
425
+ kind: "string", value: m.getCacheWarmingMode(), values: CACHE_WARMING, defaultValue: "idle",
426
426
  description: "off: never; streaming: while the agent runs; idle: also between runs while continuation stays profitable.",
427
427
  set: (v) => m.setCacheWarmingMode(str(v) as never),
428
428
  },
@@ -21,6 +21,19 @@ describe("pi settings contribution", () => {
21
21
  }
22
22
  });
23
23
 
24
+ it("cache warming row tracks pi's idle default and round-trips all modes", () => {
25
+ const m = SettingsManager.inMemory();
26
+ const row = rowAt(m, "pi.cacheWarming");
27
+ // pi 1.5.1 flipped the default from "streaming" to "idle" — a stale
28
+ // defaultValue would render the row warning-styled on a pristine config.
29
+ assert.equal(row.defaultValue, "idle");
30
+ assert.equal(row.value, "idle");
31
+ for (const v of ["streaming", "off", "idle"] as const) {
32
+ row.set(v);
33
+ assert.equal(m.getCacheWarmingMode(), v);
34
+ }
35
+ });
36
+
24
37
  it("builds OMP-taxonomy tabs with unique keys and sections", () => {
25
38
  const groups = buildPiSettingsGroups(SettingsManager.inMemory());
26
39
  const keys = groups.flatMap((g) => g.rows.map((r) => r.key));
@@ -26,6 +26,7 @@ import os from "node:os";
26
26
  import { spawn } from "node:child_process";
27
27
  import path from "node:path";
28
28
  import { skillsRoot } from "../../lib/skill-path.js";
29
+ import { childFactoryDepth, isChildSession } from "../../lib/child-session.js";
29
30
  import { nextFires, validateSchedule } from "./lib/schedule.ts";
30
31
  import {
31
32
  addJob,
@@ -505,6 +506,12 @@ export function runCronAction(args: CronActionArgs): { content: { type: "text";
505
506
  let timer: NodeJS.Timeout | undefined;
506
507
 
507
508
  export default function cronExtension(pi: ExtensionAPI) {
509
+ // Child sessions (a2a inbound dispatch, subagent child) re-run this factory
510
+ // in-process: their invocation must not re-arm the process-wide timer bound
511
+ // to the child's sendMessage — after the child disposes, that send throws
512
+ // every tick and kills host cron. Headless cron children (PI_CRON_DISABLED)
513
+ // already arm nothing.
514
+ const isChildFactory = childFactoryDepth() > 0;
508
515
  const dir = jobsDir(getAgentDir());
509
516
  // Load-time read is global-only (no ctx yet — an untrusted cwd must not arm
510
517
  // the scheduler); session_start re-reads with the trust gate below.
@@ -552,12 +559,13 @@ export default function cronExtension(pi: ExtensionAPI) {
552
559
  timer = setInterval(tick, settings.tickMs);
553
560
  timer.unref?.();
554
561
  }
555
- armTimer();
562
+ if (!isChildFactory) armTimer();
556
563
 
557
564
  // ctx (and project trust) only exists from session_start on — re-read the
558
565
  // repo scope there: a trusted repo may configure cron, an untrusted one is
559
566
  // ignored (must not re-enable the scheduler or shrink tickMs).
560
567
  pi.on("session_start", (_event, ctx) => {
568
+ if (isChildFactory || isChildSession(ctx.sessionManager)) return;
561
569
  Object.assign(
562
570
  settings,
563
571
  readCronSettings(ctx?.cwd, { project: ctx?.isProjectTrusted?.() === true }),
@@ -24,6 +24,7 @@ import * as nodePath from "node:path";
24
24
  import os from "node:os";
25
25
  import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
26
26
  import { isPlanActive } from "../../lib/plan-bridge.ts";
27
+ import { isChildSession } from "../../lib/child-session.js";
27
28
 
28
29
  /** A rule object: pattern → action. Whole-tool string rules are kept too. */
29
30
  type RuleMap = Record<string, string>;
@@ -574,5 +575,10 @@ export default function permissionModule(pi: ExtensionAPI): void {
574
575
 
575
576
  // Reset doom-loop + session-allow memory on new session so a prior session's
576
577
  // calls don't poison the new one when pi reuses the extension process.
577
- pi.on("session_start", () => { recent.length = 0; sessionAllows.clear(); resetInvalidRulesWarning(); });
578
+ pi.on("session_start", (_event, ctx) => {
579
+ // sessionAllows is MODULE-scope: an in-process child session's start must
580
+ // not wipe the host's accumulated allows (a2a child-session precedent).
581
+ if (isChildSession(ctx.sessionManager)) return;
582
+ recent.length = 0; sessionAllows.clear(); resetInvalidRulesWarning();
583
+ });
578
584
  }
@@ -58,6 +58,7 @@ import { isSqliteFile, readSqlite } from "./lib/read-sqlite.js";
58
58
  import { checkDangerousCommand, isRecord, looksLikeCodePath } from "./lib/guards.js";
59
59
  import { repairToolArguments, type RepairKind } from "./lib/input-repair.js";
60
60
  import { applyPatchToFiles, parsePatch, PatchParseError } from "./lib/patch.js";
61
+ import { isChildSession } from "../../lib/child-session.js";
61
62
  import { readRepairSettings } from "./lib/settings.js";
62
63
  import {
63
64
  extractConflictBlocks,
@@ -773,17 +774,25 @@ export default function repairModule(pi: ExtensionAPI) {
773
774
  });
774
775
 
775
776
  // ── Session lifecycle ──
776
- pi.on("session_start", () => {
777
+ pi.on("session_start", (_event, ctx) => {
778
+ // Child sessions (a2a dispatch / subagent child) must not reset the
779
+ // host's per-session repair counters, re-enable bg delivery, or abort
780
+ // the host's live background jobs from their lifecycle.
781
+ if (isChildSession(ctx.sessionManager)) return;
777
782
  // Per-session — misses from a prior session must not escalate.
778
783
  editMismatchCounts.clear();
779
784
  repairCounts.clear();
780
785
  });
781
786
  if (autoBgOn) {
782
- pi.on("session_start", () => setBgDeliveryEnabled(true));
787
+ pi.on("session_start", (_event, ctx) => {
788
+ if (isChildSession(ctx.sessionManager)) return;
789
+ setBgDeliveryEnabled(true);
790
+ });
783
791
  // Delivery is suppressed so the aborts don't fire triggerTurn follow-ups
784
792
  // into a session that is going away (/new and /resume also fire
785
793
  // session_shutdown, so cross-session leakage can't happen).
786
- pi.on("session_shutdown", () => {
794
+ pi.on("session_shutdown", (_event, ctx) => {
795
+ if (isChildSession(ctx.sessionManager)) return;
787
796
  abortAllBgJobs(true);
788
797
  });
789
798
  }
@@ -4,8 +4,13 @@ import { migrateLegacyConfig } from "./lib/migrate.js";
4
4
  import { registerProvider, maybeRefreshCatalog } from "./lib/provider.js";
5
5
  import { refreshActiveModel } from "./lib/refresh.js";
6
6
  import { registerCommands } from "./commands/commands.js";
7
+ import { childFactoryDepth, isChildSession } from "../../lib/child-session.js";
7
8
 
8
9
  export default function (pi: ExtensionAPI) {
10
+ // Child sessions (a2a dispatch / subagent child) re-run this factory
11
+ // in-process: skip their catalog refresh interval entirely (it would hold
12
+ // the child's ctx alive and re-register the provider per dispatch).
13
+ const isChildFactory = childFactoryDepth() > 0;
9
14
  // Base URL the currently-registered provider was built with — session_start
10
15
  // compares against it to detect a trust-gated repo override (see below).
11
16
  let registeredBaseUrl = "";
@@ -31,13 +36,19 @@ export default function (pi: ExtensionAPI) {
31
36
  // Uses the latest session ctx (ExtensionAPI carries no modelRegistry).
32
37
  // ponytail: 5-min tick + 15-min TTL constants, no env knob until asked.
33
38
  let lastCtx: ExtensionContext | undefined;
34
- const periodicRefresh = setInterval(() => {
35
- if (!lastCtx) return;
36
- void maybeRefreshCatalog(lastCtx).catch(() => { /* transient — next tick retries */ });
37
- }, 5 * 60_000);
38
- periodicRefresh.unref?.();
39
+ if (!isChildFactory) {
40
+ const periodicRefresh = setInterval(() => {
41
+ if (!lastCtx) return;
42
+ void maybeRefreshCatalog(lastCtx).catch(() => { /* transient — next tick retries */ });
43
+ }, 5 * 60_000);
44
+ periodicRefresh.unref?.();
45
+ }
39
46
 
40
47
  pi.on("session_start", async (_event, ctx) => {
48
+ // In-process child sessions (a2a dispatch / subagent child) inherit the
49
+ // host's model + modelRegistry — their session_start must not re-register
50
+ // the provider or pull the catalog (a network fetch per dispatch).
51
+ if (isChildSession(ctx.sessionManager)) return;
41
52
  lastCtx = ctx;
42
53
  // Now ctx exists: trust-gate the repo scope. A trusted repo may add/override
43
54
  // the endpoint; an untrusted one is ignored (attacker-redirect guard).
@@ -70,6 +81,9 @@ export default function (pi: ExtensionAPI) {
70
81
 
71
82
  // Stop the interval from refreshing with a dead session's registry after
72
83
  // quit/reload/session replacement (review finding 4).
73
- pi.on("session_shutdown", () => { lastCtx = undefined; });
84
+ pi.on("session_shutdown", (_event, ctx) => {
85
+ if (isChildSession(ctx.sessionManager)) return;
86
+ lastCtx = undefined;
87
+ });
74
88
  }
75
89
 
@@ -15,6 +15,7 @@ const MAX_CHARS_PARAM = Type.Optional(Type.Number({ description: "Max response c
15
15
  const TIMEOUT_MS_PARAM = Type.Optional(Type.Number({ description: "Timeout in ms." }));
16
16
 
17
17
  import { truncateText } from "./lib/truncate";
18
+ import { isChildSession } from "../../lib/child-session.js";
18
19
 
19
20
  const controlSchema = {
20
21
  project: PROJECT_PARAM,
@@ -602,8 +603,9 @@ export default function serenaToolsExtension(pi: ExtensionAPI) {
602
603
 
603
604
  // session_shutdown fires only on parent lifecycle events (reload/quit/new/fork/
604
605
  // resume) — child sessions (pi-subagent) use dispose() which does NOT emit it.
605
- // So stopping here is safe: it never runs for children, and the module-level
606
- // singleton means children reuse this worker without spawning their own.
606
+ // EXCEPTION: a2a inbound dispatches DO emit session_shutdown from their runner
607
+ // (leak fix for stdio MCP servers) — the isChildSession guard keeps them from
608
+ // stopping the HOST's worker (module-level singleton, shared process).
607
609
  //
608
610
  // ponytail: known race — if a child is mid-serena-request when the parent
609
611
  // reloads, worker.stop() rejects that request with "Serena worker stopped"
@@ -613,6 +615,7 @@ export default function serenaToolsExtension(pi: ExtensionAPI) {
613
615
  // the worker across parent+children was considered and rejected as
614
616
  // over-engineering for a cosmetic error-text difference during teardown.
615
617
  pi.on("session_shutdown", async (_event, ctx) => {
618
+ if (isChildSession(ctx.sessionManager)) return;
616
619
  try {
617
620
  await worker?.stop();
618
621
  } catch {
@@ -67,6 +67,7 @@ import {
67
67
  } from "./lib/security.ts";
68
68
  import {
69
69
  aggregateUsage,
70
+ expandKeyLabel,
70
71
  formatUsageStats,
71
72
  renderSingleResult,
72
73
  } from "./lib/render.ts";
@@ -88,6 +89,7 @@ import { startBackgroundTask,
88
89
  } from "./lib/background.ts";
89
90
  import { parseStructuredResult } from "./lib/result.ts";
90
91
  import { skillsRoot } from "../../lib/skill-path.js";
92
+ import { isChildSession } from "../../lib/child-session.js";
91
93
  import { appendHistory, readHistory, markInterruptedOnRestart, trimHistory, getHistoryPath } from "./lib/history.ts";
92
94
  import { herdrCli } from './lib/herdr.ts';
93
95
  /** Keep-alive cadence for herdr delegations (test seam: shorten to assert). */
@@ -302,6 +304,12 @@ export default function (pi: ExtensionAPI) {
302
304
  // Invalidate agent cache + clear thread store on session replacement.
303
305
  pi.on("session_start", (event, ctx) => {
304
306
  currentCtx = ctx;
307
+ // A child session's start must not wipe the HOST's MODULE-scope state:
308
+ // threadStore (live widget rows) or the trusted-agent-dir cache — and its
309
+ // factory instance legitimately keeps its own currentCtx for sub-dispatch.
310
+ // Everything below is module-scope or process-wide (history file, git
311
+ // sweeps, the /config bridge) and stays host-owned.
312
+ if (isChildSession(ctx.sessionManager)) return;
305
313
  if (event.reason === "reload") invalidateAgentCache();
306
314
  threadStore.clear();
307
315
  trustedProjectAgentDirs.clear();
@@ -326,7 +334,8 @@ export default function (pi: ExtensionAPI) {
326
334
  });
327
335
 
328
336
  // Clear the widget + abort background tasks on shutdown.
329
- pi.on("session_shutdown", () => {
337
+ pi.on("session_shutdown", (_event, ctx) => {
338
+ if (isChildSession(ctx.sessionManager)) return;
330
339
  widget.dispose();
331
340
  clearBackgroundTasks();
332
341
  });
@@ -1769,6 +1778,7 @@ ${lines.join("\n")}`;
1769
1778
  const scope: AgentScope = args.agentScope ?? "user";
1770
1779
  const fg = theme.fg.bind(theme);
1771
1780
  const now = Date.now();
1781
+ const expandKey = expandKeyLabel(context);
1772
1782
 
1773
1783
  // Live-render driver: while the tool executes, re-render every second
1774
1784
  // (bash.js pattern) so elapsed + tool-call count stay fresh in the TUI.
@@ -1832,7 +1842,7 @@ ${lines.join("\n")}`;
1832
1842
  live;
1833
1843
  }
1834
1844
  if (args.chain.length > cap)
1835
- text += `\n ${fg("muted", `... +${args.chain.length - cap} more${context.expanded ? "" : " (Ctrl+O to expand)"}`)}`;
1845
+ text += `\n ${fg("muted", `... +${args.chain.length - cap} more${context.expanded ? "" : ` (${expandKey} to expand)`}`)}`;
1836
1846
  return new Text(text, 0, 0);
1837
1847
  }
1838
1848
 
@@ -1851,7 +1861,7 @@ ${lines.join("\n")}`;
1851
1861
  text += `\n ${fg(resolveAgentColor(t.agent), t.agent)}${fg("dim", ` ${preview}`)}${live}`;
1852
1862
  }
1853
1863
  if (args.tasks.length > cap)
1854
- text += `\n ${fg("muted", `... +${args.tasks.length - cap} more${context.expanded ? "" : " (Ctrl+O to expand)"}`)}`;
1864
+ text += `\n ${fg("muted", `... +${args.tasks.length - cap} more${context.expanded ? "" : ` (${expandKey} to expand)`}`)}`;
1855
1865
  return new Text(text, 0, 0);
1856
1866
  }
1857
1867
 
@@ -1890,11 +1900,13 @@ ${lines.join("\n")}`;
1890
1900
 
1891
1901
  const fg = theme.fg.bind(theme);
1892
1902
  const mdTheme = getMarkdownTheme();
1903
+ // Host-configured expand key (pi 1.5.x KeybindingHints); literal on older pi.
1904
+ const expandKey = expandKeyLabel(_context);
1893
1905
 
1894
1906
  // --- Single ---
1895
1907
  if (details.mode === "single" && details.results.length === 1) {
1896
1908
  const r = details.results[0];
1897
- return renderSingleResult(r, expanded, theme, resolveAgentColor(r.agent));
1909
+ return renderSingleResult(r, expanded, theme, resolveAgentColor(r.agent), expandKey);
1898
1910
  }
1899
1911
 
1900
1912
  // --- Chain ---
@@ -1963,7 +1975,7 @@ ${lines.join("\n")}`;
1963
1975
  }
1964
1976
  const totalUsage = formatUsageStats(aggregateUsage(details.results));
1965
1977
  if (totalUsage) text += `\n${fg("dim", totalUsage)}`;
1966
- text += `\n${fg("muted", "(Ctrl+O to expand)")}`;
1978
+ text += `\n${fg("muted", `(${expandKey} to expand)`)}`;
1967
1979
  return new Text(text, 0, 0);
1968
1980
  }
1969
1981
 
@@ -2048,7 +2060,7 @@ ${lines.join("\n")}`;
2048
2060
  const totalUsage = formatUsageStats(aggregateUsage(details.results));
2049
2061
  if (totalUsage) text += `\n${fg("dim", totalUsage)}`;
2050
2062
  }
2051
- if (!expanded) text += `\n${fg("muted", "(Ctrl+O to expand)")}`;
2063
+ if (!expanded) text += `\n${fg("muted", `(${expandKey} to expand)`)}`;
2052
2064
  return new Text(text, 0, 0);
2053
2065
  }
2054
2066
 
@@ -31,6 +31,21 @@ export function asRecord(value: unknown): Record<string, unknown> {
31
31
  : {};
32
32
  }
33
33
 
34
+ /**
35
+ * The configured key(s) that toggle tool output, for `(… to expand)` hints.
36
+ * pi 1.5.x hands every tool render context a `keyText`/`keyHint` pair that
37
+ * resolves the HOST's keybindings (`app.tools.expand`, ctrl+o by default), so
38
+ * a user rebind is reflected instead of a hardcoded "Ctrl+O". Contexts without
39
+ * it (pi <1.5, widget/thread renderers) keep the literal.
40
+ */
41
+ export function expandKeyLabel(context?: { keyText?: (k: "app.tools.expand") => string }): string {
42
+ try {
43
+ return context?.keyText?.("app.tools.expand") || "Ctrl+O";
44
+ } catch {
45
+ return "Ctrl+O";
46
+ }
47
+ }
48
+
34
49
  // ---------------------------------------------------------------------------
35
50
  // Display helpers
36
51
  // ---------------------------------------------------------------------------
@@ -214,6 +229,8 @@ export function renderSingleResult(
214
229
  expanded: boolean,
215
230
  theme: { fg: (c: any, t: string) => string; bold: (t: string) => string },
216
231
  agentColor?: string,
232
+ /** Configured expand key label — see expandKeyLabel(). */
233
+ expandKey = "Ctrl+O",
217
234
  ): Container | Text {
218
235
  const isError = isFailedResult(result);
219
236
  const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
@@ -299,7 +316,7 @@ export function renderSingleResult(
299
316
  text += `\n${theme.fg("muted", "(no output)")}`;
300
317
  } else if (rawOutput.trim() !== "") {
301
318
  // All-structural output (headings/bullets/fences only) — still say so.
302
- text += `\n${theme.fg("dim", "⎿ (markdown answer — Ctrl+O to view)")}`;
319
+ text += `\n${theme.fg("dim", `⎿ (markdown answer — ${expandKey} to view)`)}`;
303
320
  }
304
321
  } else if (!result.errorMessage && rawOutput.trim() === "" && !result.stderr) {
305
322
  // Error with no message, no stderr, no assistant output — say so.
@@ -312,7 +329,7 @@ export function renderSingleResult(
312
329
  // Hint: getResultOutput always returns at least "(no output)", so finalOutput
313
330
  // is always truthy — show the hint whenever there's any trace to expand.
314
331
  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)")}`;
332
+ text += `\n${theme.fg("muted", `(${expandKey} to expand · /agent for full thread)`)}`;
316
333
  }
317
334
  return new Text(text, 0, 0);
318
335
  }
@@ -31,6 +31,7 @@ import {
31
31
  SessionManager,
32
32
  SettingsManager,
33
33
  } from "@earendil-works/pi-coding-agent";
34
+ import { beginChildFactory, endChildFactory, markChildSession } from "../../../lib/child-session.js";
34
35
  import {
35
36
  classifyStopReason,
36
37
  createCombinedAbortSignal,
@@ -96,7 +97,12 @@ async function getExtensionLoader(cwd: string, projectTrusted: boolean): Promise
96
97
  noContextFiles: true,
97
98
  noThemes: true,
98
99
  });
99
- await loader.reload({ resolveProjectTrust: async () => projectTrusted });
100
+ beginChildFactory();
101
+ try {
102
+ await loader.reload({ resolveProjectTrust: async () => projectTrusted });
103
+ } finally {
104
+ endChildFactory();
105
+ }
100
106
  // Log (don't throw on) extension load errors — a misbehaving extension must
101
107
  // not crash the child; the agent simply won't have that tool.
102
108
  const loadErrors = loader.getExtensions().errors;
@@ -213,6 +219,13 @@ export async function runSubAgent(options: {
213
219
  getAppendSystemPrompt: () => [], getAppendSystemPromptSources: () => [],
214
220
  extendResources: () => {}, reload: async () => {},
215
221
  };
222
+ // In-process child: ceulen's factories re-ran inside getExtensionLoader's
223
+ // reload() and this session's lifecycle events share the host's ES-module
224
+ // scope — mark it so host-owned handlers drop the child's events (a2a
225
+ // inbound-dispatch precedent). The lean stub path never runs factories, so
226
+ // it needs no marking.
227
+ const childSessionManager = SessionManager.inMemory(cwd);
228
+ if (loadExtensions) markChildSession(childSessionManager);
216
229
  const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: true, maxRetries: 1 } });
217
230
  const startedAt = Date.now();
218
231
  let inactivityDeadline = startedAt + timeoutMs;
@@ -288,7 +301,7 @@ export async function runSubAgent(options: {
288
301
  let session: Awaited<ReturnType<typeof createAgentSession>>["session"];
289
302
  try {
290
303
  const created = await createAgentSession({
291
- cwd: childCwd, model, thinkingLevel, resourceLoader, tools, sessionManager: SessionManager.inMemory(childCwd), settingsManager,
304
+ cwd: childCwd, model, thinkingLevel, resourceLoader, tools, sessionManager: childSessionManager, settingsManager,
292
305
  ...(modelRuntime ? { modelRuntime } : {}),
293
306
  // Pi 0.80.10 owns credentials in ModelRuntime; older SDKs still accept these.
294
307
  ...(authStorage ? { authStorage, modelRegistry } : {}),
@@ -0,0 +1,50 @@
1
+ // Expand-hint rendering: the "(… to expand)" hint follows the HOST's
2
+ // configured keybinding (pi 1.5.x `KeybindingHints.keyText`) and falls back to
3
+ // the literal "Ctrl+O" when no render context supplies one (pi <1.5, widget and
4
+ // thread renderers). A null theme renders plain text, so assertions read the
5
+ // raw strings — same convention as widget.test.ts.
6
+
7
+ import assert from "node:assert/strict";
8
+ import { test } from "node:test";
9
+ import { expandKeyLabel, renderSingleResult } from "../lib/render.ts";
10
+ import type { SubAgentResult } from "../lib/runner.ts";
11
+ import type { Text } from "@earendil-works/pi-tui";
12
+
13
+ const plainTheme = {
14
+ fg: (_c: string, text: string) => text,
15
+ bold: (text: string) => text,
16
+ };
17
+
18
+ function result(overrides: Partial<SubAgentResult> = {}): SubAgentResult {
19
+ return {
20
+ agent: "scout",
21
+ task: "Recon the registry module",
22
+ exitCode: 0,
23
+ messages: [],
24
+ stderr: "",
25
+ usage: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0, cost: 0.01, contextTokens: 3, turns: 1 },
26
+ ...overrides,
27
+ };
28
+ }
29
+
30
+ const renderText = (component: unknown): string => (component as Text).render(100).join("\n");
31
+
32
+ test("expandKeyLabel: host keybinding wins, literal is the fallback", () => {
33
+ assert.equal(expandKeyLabel({ keyText: () => "ctrl+o" }), "ctrl+o");
34
+ assert.equal(expandKeyLabel({ keyText: () => "" }), "Ctrl+O", "empty key list falls back");
35
+ assert.equal(expandKeyLabel({ keyText: () => { throw new Error("boom"); } }), "Ctrl+O", "throwing context falls back");
36
+ assert.equal(expandKeyLabel(undefined), "Ctrl+O", "no context (widget/thread renderers, older pi)");
37
+ });
38
+
39
+ test("renderSingleResult: collapsed hint uses the configured expand key", () => {
40
+ const r = result({
41
+ messages: [{ role: "assistant", content: [{ type: "text", text: "## Heading only" }] } as never],
42
+ });
43
+ // Host-configured key (a rebind) replaces the hardcoded literal.
44
+ const rebinded = renderText(renderSingleResult(r, false, plainTheme, undefined, "ctrl+shift+e"));
45
+ assert.match(rebinded, /ctrl\+shift\+e to expand/);
46
+ assert.doesNotMatch(rebinded, /Ctrl\+O/);
47
+ // Default parameter keeps today's behavior for callers without a context.
48
+ const fallback = renderText(renderSingleResult(r, false, plainTheme));
49
+ assert.match(fallback, /Ctrl\+O to expand/);
50
+ });
@@ -5,6 +5,7 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { loadCwdEnvFilesIfTrusted, parseEnvText } from "../../lib/env.js";
7
7
  import { resetGenRate, setGenRate } from "../../lib/rate.js";
8
+ import { isChildSession } from "../../lib/child-session.js";
8
9
  import { resetUsageItem, setUsageItem } from "../../lib/usage-store.js";
9
10
  /** Single source of truth for User-Agent strings — matches package.json version. */
10
11
  const CEULEN_VERSION: string = (() => {
@@ -1932,6 +1933,11 @@ export default function (pi: ExtensionAPI) {
1932
1933
  const state: State = { lastRefreshAt: 0, refreshGeneration: 0, cumulativeOutput: 0, cumulativeDurationMs: 0, cumulativeCost: 0 };
1933
1934
 
1934
1935
  pi.on("session_start", async (_event, ctx) => {
1936
+ // state.ctx is factory-scope, but the usage/rate stores it resets are
1937
+ // MODULE-scope (shared with the composer band). An in-process child
1938
+ // session (a2a dispatch, subagent child) must not reset the host's
1939
+ // quota/rate band items or re-target the footer ctx.
1940
+ if (isChildSession(ctx.sessionManager)) return;
1935
1941
  // Cwd .env files are untrusted repo content — ingest only for trusted
1936
1942
  // projects (idempotent; first trusted session wins).
1937
1943
  loadCwdEnvFilesIfTrusted(ctx);
@@ -1957,16 +1963,22 @@ export default function (pi: ExtensionAPI) {
1957
1963
  });
1958
1964
 
1959
1965
  pi.on("model_select", async (event, _ctx) => {
1966
+ if (isChildSession(_ctx.sessionManager)) return;
1960
1967
  updateActiveAdapter(state, event.model);
1961
1968
  if (state.adapter) deferRefresh(state, true);
1962
1969
  });
1963
1970
 
1964
1971
  pi.on("before_provider_request", async (_event, _ctx) => {
1972
+ if (isChildSession(_ctx.sessionManager)) return;
1965
1973
  state.responseStartPerf = performance.now();
1966
1974
  });
1967
1975
 
1968
1976
  pi.on("message_end", async (event, _ctx) => {
1969
1977
  if (event.message.role === "assistant") {
1978
+ // Child sessions (a2a dispatch / subagent child in this process) share
1979
+ // these factory-scope accumulators and the module-scope rate store —
1980
+ // their turns must not feed the host's tok/s, cost totals, or footer.
1981
+ if (isChildSession(_ctx.sessionManager)) return;
1970
1982
  // pi-budget parity: coerce + finite guard so a string/NaN cost.total can
1971
1983
  // never poison the accumulator (string concat garbles every subsequent
1972
1984
  // footer).
@@ -1996,6 +2008,7 @@ export default function (pi: ExtensionAPI) {
1996
2008
  });
1997
2009
 
1998
2010
  pi.on("after_provider_response", async (event, _ctx) => {
2011
+ if (isChildSession(_ctx.sessionManager)) return;
1999
2012
  if (event.status >= 400) {
2000
2013
  state.responseStartPerf = undefined;
2001
2014
  }
@@ -2003,6 +2016,10 @@ export default function (pi: ExtensionAPI) {
2003
2016
  });
2004
2017
 
2005
2018
  pi.on("session_shutdown", async (_event, ctx) => {
2019
+ // Child sessions never installed state.ctx (guarded above) — but keep
2020
+ // the identity check first so a child's shutdown can never clear the
2021
+ // host's ctx / status / usage item.
2022
+ if (isChildSession(ctx.sessionManager)) return;
2006
2023
  // Only tear down if this shutdown belongs to the installed session: a late
2007
2024
  // old-session shutdown (delivered after the next session_start) must not
2008
2025
  // stop the live refresh timer, drop the live in-flight fetch, or touch a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.26.0",
3
+ "version": "0.26.2",
4
4
  "description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "homepage": "https://github.com/ceulen-dev/ceulen#readme",
41
41
  "bugs": "https://github.com/ceulen-dev/ceulen/issues",
42
42
  "scripts": {
43
- "test": "node scripts/validate-themes.mjs && node --import tsx --test extensions/lib/env.test.ts extensions/lib/order.test.ts extensions/lib/registry.test.ts extensions/lib/skill-path.test.ts extensions/modules/router/test/unit.test.ts extensions/modules/router/test/guard.test.ts extensions/modules/classifier/test/*.test.ts extensions/modules/advisor/test/*.test.ts extensions/modules/usage/test/*.test.ts extensions/modules/ponytail/test/*.test.ts extensions/modules/ux/test/*.test.ts extensions/modules/config/test/*.test.ts extensions/modules/composer/test/*.test.ts extensions/modules/serena/test/*.test.ts extensions/modules/fff/test/*.test.ts extensions/modules/rtk/test/*.test.js extensions/modules/munin/test/*.test.ts extensions/modules/subagent/test/*.test.ts extensions/modules/zai/test/*.test.ts extensions/modules/repair/test/*.test.ts extensions/modules/steering/test/*.test.ts extensions/modules/plan/test/*.test.ts extensions/modules/todo/test/*.test.ts extensions/modules/web/test/*.test.ts extensions/modules/rules/test/*.test.ts extensions/modules/a2a/test/*.test.ts extensions/modules/gh/test/*.test.ts extensions/modules/attachments/test/*.test.ts extensions/modules/cron/test/*.test.ts extensions/modules/goal/test/*.test.ts extensions/modules/permission/test/*.test.ts extensions/modules/shells/test/*.test.ts extensions/modules/sg/test/*.test.ts extensions/modules/jfind/test/*.test.ts extensions/modules/notify/test/*.test.ts",
43
+ "test": "node scripts/validate-themes.mjs && node --import tsx --test extensions/lib/env.test.ts extensions/lib/order.test.ts extensions/lib/registry.test.ts extensions/lib/skill-path.test.ts extensions/lib/child-session.test.ts extensions/modules/router/test/unit.test.ts extensions/modules/router/test/guard.test.ts extensions/modules/classifier/test/*.test.ts extensions/modules/advisor/test/*.test.ts extensions/modules/usage/test/*.test.ts extensions/modules/ponytail/test/*.test.ts extensions/modules/ux/test/*.test.ts extensions/modules/config/test/*.test.ts extensions/modules/composer/test/*.test.ts extensions/modules/serena/test/*.test.ts extensions/modules/fff/test/*.test.ts extensions/modules/rtk/test/*.test.js extensions/modules/munin/test/*.test.ts extensions/modules/subagent/test/*.test.ts extensions/modules/zai/test/*.test.ts extensions/modules/repair/test/*.test.ts extensions/modules/steering/test/*.test.ts extensions/modules/plan/test/*.test.ts extensions/modules/todo/test/*.test.ts extensions/modules/web/test/*.test.ts extensions/modules/rules/test/*.test.ts extensions/modules/a2a/test/*.test.ts extensions/modules/gh/test/*.test.ts extensions/modules/attachments/test/*.test.ts extensions/modules/cron/test/*.test.ts extensions/modules/goal/test/*.test.ts extensions/modules/permission/test/*.test.ts extensions/modules/shells/test/*.test.ts extensions/modules/sg/test/*.test.ts extensions/modules/jfind/test/*.test.ts extensions/modules/notify/test/*.test.ts",
44
44
  "typecheck": "tsc --noEmit"
45
45
  },
46
46
  "pi": {
@@ -0,0 +1,55 @@
1
+ // Live probe for the child-session contamination fix (run with tsx).
2
+ // Reproduces the incident's exact mechanism in-process:
3
+ // 1. Fire ceulen composer's host session_start (module-scope liveCtx installed).
4
+ // 2. Create a child pi session through the SAME SDK path the a2a runner uses
5
+ // (DefaultResourceLoader.reload → createAgentSession → bindExtensions print),
6
+ // marking it like makeSessionRunner does.
7
+ // 3. Emit the child's session_shutdown + dispose.
8
+ // 4. Assert the host liveCtx survived (pre-fix it was undefined → blank band).
9
+ import composerModule, { __liveCtxForTests } from "../extensions/modules/composer/index.ts";
10
+ import { markChildSession } from "../extensions/lib/child-session.ts";
11
+
12
+ const handlers = new Map();
13
+ composerModule({
14
+ on: (event, handler) => handlers.set(event, [...(handlers.get(event) ?? []), handler]),
15
+ getSettings: () => ({ compaction: { enabled: true } }),
16
+ });
17
+ const hostCtx = {
18
+ mode: "tui",
19
+ hasUI: true,
20
+ cwd: process.cwd(),
21
+ sessionManager: { id: "host" },
22
+ thinkingLevel: "medium",
23
+ ui: { theme: { fg: (_c, s) => s, bold: (s) => s }, notify() {}, setStatus() {}, setWidget() {}, setEditorComponent() {}, setFooter() {} },
24
+ };
25
+ for (const h of handlers.get("session_start")) await h({}, hostCtx);
26
+ if (__liveCtxForTests() !== hostCtx) throw new Error("probe setup failed: liveCtx not installed");
27
+ console.log("host liveCtx installed ✓");
28
+
29
+ // Child session — the a2a makeSessionRunner path (ceulen is the installed
30
+ // package in this agent dir, so the child loads the same bundle).
31
+ const sdk = await import("@earendil-works/pi-coding-agent");
32
+ const { createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader } = sdk;
33
+ const loader = new DefaultResourceLoader({ cwd: process.cwd(), agentDir: sdk.getAgentDir() });
34
+ await loader.reload({ resolveProjectTrust: async () => true });
35
+ const sm = SessionManager.inMemory(process.cwd(), { id: "task-probe" });
36
+ markChildSession(sm);
37
+ const created = await createAgentSession({
38
+ cwd: process.cwd(),
39
+ model: undefined,
40
+ resourceLoader: loader,
41
+ sessionManager: sm,
42
+ settingsManager: SettingsManager.inMemory({}),
43
+ });
44
+ const session = created.session;
45
+ await session.bindExtensions({ mode: "print" });
46
+ console.log("child bound ✓");
47
+ await session.extensionRunner?.emit({ type: "session_shutdown", reason: "quit" });
48
+ await session.dispose();
49
+
50
+ if (__liveCtxForTests() !== hostCtx) {
51
+ console.error("FAIL: host liveCtx was clobbered by the child lifecycle (the incident)");
52
+ process.exit(1);
53
+ }
54
+ console.log("host liveCtx survived the child session ✓ — fix verified");
55
+ process.exit(0);