ceulen 0.25.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,59 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.26.1 — 2026-11-04
4
+
5
+ **Fix: inbound A2A dispatches blanked the host TUI's status band (model ·
6
+ cwd · git · context) until restart.**
7
+
8
+ Root cause: each inbound dispatch runs a child pi session **in this
9
+ process** (`makeSessionRunner` → `bindExtensions({mode:"print"})` fires the
10
+ child's `session_start`; the dispose path emits `session_shutdown`). Pi
11
+ re-invokes ceulen's module factories for the child while ES-module scope
12
+ stays shared — so the child's lifecycle clobbered host module-scope state.
13
+ Worst hit: composer's `liveCtx` (child shutdown cleared it → the status
14
+ band renders blank; band shapes had replaced pi's native footer, so ALL
15
+ identity info vanished — the reported screenshot). Same family: the
16
+ child's shutdown cleared the classifier registry (host `classify`/
17
+ planGate/thinkGate stopped resolving), killed the host's background
18
+ subagent tasks and auto-bg bash jobs, stopped the shared serena worker,
19
+ reset the usage/rate band items, fed child turns into the host's tok/s +
20
+ cost totals, and re-armed cron's process timer + router's catalog interval
21
+ onto the disposed child.
22
+
23
+ Fix: `extensions/lib/child-session.ts` — a `markChildSession`
24
+ WeakSet (a2a's runner + subagent's extension-loading runner mark their
25
+ child session managers) + `beginChildFactory()/endChildFactory()` depth
26
+ window around the loaders' `reload()`. Handlers that write module-scope or
27
+ process-wide state gate on `isChildSession(ctx.sessionManager)`; factory-
28
+ time arms (cron's interval, router's catalog refresh) gate on
29
+ `childFactoryDepth()`. Gated modules: composer, classifier, usage,
30
+ subagent, cron, serena, router, permission, repair. Children keep their
31
+ tools and per-turn handlers (steering, fff, repair arg-fixing) — only
32
+ host-owned bookkeeping is protected.
33
+
34
+ Verified: unit + integration tests (`child-session.test.ts`, a2a
35
+ `child-contamination.test.ts` — drives the real composer handlers), and a
36
+ live SDK probe (`scripts/child-session-probe.ts`) that creates a real
37
+ child session through the exact a2a runner path and asserts the host's
38
+ `liveCtx` survives the full child lifecycle. Full suite 2956/0 fail.
39
+
40
+ ## 0.26.0 — 2026-11-03
41
+
42
+ Pi 1.5.0 support (peer range was `<1.5.0`, which semver-excluded the new
43
+ release).
44
+
45
+ - **Peer deps widened** to `>=0.99.1 <1.6.0` (both pi packages) — pi 1.5.0
46
+ + pi-tui 1.5.0 verified surface-by-surface: the pi-schema tool-argument
47
+ validation change is inert to ceulen (repair's `prepareArguments` hook
48
+ still runs before validation; repair reads only error paths, never
49
+ messages; hidden `__mt*` markers stay non-enumerable; no exotic TypeBox
50
+ features anywhere in the bundle).
51
+ - **`changelogPath` added** to the `pi` manifest — pi 1.5.0's new
52
+ "Extension Updates" notice now shows ceulen's changes after
53
+ `pi update --extensions`.
54
+ - Verified: tsc clean, 2951 tests pass / 0 fail, live rpc-mode smoke on
55
+ pi 1.5.0 (60 commands, `/ceulen` handled, zero stderr).
56
+
3
57
  ## 0.25.0 — 2026-11-01
4
58
 
5
59
  Goal module (`extensions/modules/goal/`): OMP/Codex-style **autonomous
@@ -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
  }
@@ -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 {
@@ -88,6 +88,7 @@ import { startBackgroundTask,
88
88
  } from "./lib/background.ts";
89
89
  import { parseStructuredResult } from "./lib/result.ts";
90
90
  import { skillsRoot } from "../../lib/skill-path.js";
91
+ import { isChildSession } from "../../lib/child-session.js";
91
92
  import { appendHistory, readHistory, markInterruptedOnRestart, trimHistory, getHistoryPath } from "./lib/history.ts";
92
93
  import { herdrCli } from './lib/herdr.ts';
93
94
  /** Keep-alive cadence for herdr delegations (test seam: shorten to assert). */
@@ -302,6 +303,12 @@ export default function (pi: ExtensionAPI) {
302
303
  // Invalidate agent cache + clear thread store on session replacement.
303
304
  pi.on("session_start", (event, ctx) => {
304
305
  currentCtx = ctx;
306
+ // A child session's start must not wipe the HOST's MODULE-scope state:
307
+ // threadStore (live widget rows) or the trusted-agent-dir cache — and its
308
+ // factory instance legitimately keeps its own currentCtx for sub-dispatch.
309
+ // Everything below is module-scope or process-wide (history file, git
310
+ // sweeps, the /config bridge) and stays host-owned.
311
+ if (isChildSession(ctx.sessionManager)) return;
305
312
  if (event.reason === "reload") invalidateAgentCache();
306
313
  threadStore.clear();
307
314
  trustedProjectAgentDirs.clear();
@@ -326,7 +333,8 @@ export default function (pi: ExtensionAPI) {
326
333
  });
327
334
 
328
335
  // Clear the widget + abort background tasks on shutdown.
329
- pi.on("session_shutdown", () => {
336
+ pi.on("session_shutdown", (_event, ctx) => {
337
+ if (isChildSession(ctx.sessionManager)) return;
330
338
  widget.dispose();
331
339
  clearBackgroundTasks();
332
340
  });
@@ -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 } : {}),
@@ -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.25.0",
3
+ "version": "0.26.1",
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,10 +40,11 @@
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": {
47
+ "changelogPath": "./CHANGELOG.md",
47
48
  "extensions": [
48
49
  "./extensions"
49
50
  ],
@@ -52,8 +53,8 @@
52
53
  ]
53
54
  },
54
55
  "peerDependencies": {
55
- "@earendil-works/pi-coding-agent": ">=0.99.1 <1.5.0",
56
- "@earendil-works/pi-tui": ">=0.99.1 <1.5.0",
56
+ "@earendil-works/pi-coding-agent": ">=0.99.1 <1.6.0",
57
+ "@earendil-works/pi-tui": ">=0.99.1 <1.6.0",
57
58
  "typebox": "*"
58
59
  },
59
60
  "devDependencies": {
@@ -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);