Skip to content

Commit 0f6bd55

Browse files
fix(pi): load only lifecycle markers ahead of user extensions
Prepending the whole T3 bridge so its session_start marker ran first also moved the MCP and permission bridge ahead of user extensions, changing tool and permission hook precedence. Split the markers into a minimal lifecycle sentinel that loads first, and keep the bridge at its original final position. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e597c64 commit 0f6bd55

5 files changed

Lines changed: 150 additions & 74 deletions

File tree

‎packages/provider-pi/src/server/adapter.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
472472
// The extension owns both the optional MCP bridge and Pi's permission
473473
// hook. Materialize it even when this session has no MCP credential so
474474
// Supervised never silently degrades to unrestricted tool execution.
475-
const extensionPath = yield* provideCacheFs(
475+
const { extensionPath, lifecycleExtensionPath } = yield* provideCacheFs(
476476
materializePiT3McpExtension(host.paths.providerStatusCacheDir),
477477
);
478478
const resolvedLaunchArgs = resolvePiLaunchArgs(options.settings.launchArgs);
@@ -484,6 +484,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
484484
environment: options.environment,
485485
mcpSession,
486486
extensionPath,
487+
lifecycleExtensionPath,
487488
runtimeMode: input.runtimePolicy.runtimeMode,
488489
});
489490
const scopedLaunch = yield* agentScope.wrap({

‎packages/provider-pi/src/server/mcpExtensionSource.test.ts‎

Lines changed: 62 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ import * as NodeModule from "node:module";
66
import * as NodeVM from "node:vm";
77
import { assert, describe, it } from "@effect/vitest";
88

9-
import { PI_T3_MCP_EXTENSION_SOURCE, PI_T3_SESSION_END_STATUS_KEY } from "./mcpExtensionSource.ts";
9+
import {
10+
PI_T3_LIFECYCLE_EXTENSION_SOURCE,
11+
PI_T3_MCP_EXTENSION_SOURCE,
12+
PI_T3_SESSION_END_STATUS_KEY,
13+
PI_T3_SESSION_START_STATUS_KEY,
14+
} from "./mcpExtensionSource.ts";
1015
import { loadMcpBridge } from "./mcpBridge.testkit.ts";
1116

1217
type RequestHook = (
@@ -78,33 +83,62 @@ describe("Pi orchestration prompt section", () => {
7883
});
7984

8085
describe("Pi session teardown", () => {
81-
it.each(["MCP", "permission-only"])(
82-
"marks shutdown and replacement start with %s",
83-
async (mode) => {
84-
const handlers = mode === "MCP" ? (await loadMcpBridge()).handlers : await loadHooks();
85-
const statuses: Array<readonly [string, string | undefined]> = [];
86-
const ui = {
87-
notify: () => undefined,
88-
setStatus: (key: string, text: string | undefined) => statuses.push([key, text]),
89-
};
90-
type LifecycleHook = (
91-
event: { systemPrompt: string; reason?: string },
92-
ctx: { ui: typeof ui },
93-
) => unknown;
94-
const shutdown = handlers.get("session_shutdown") as LifecycleHook;
95-
const start = handlers.get("session_start") as LifecycleHook;
96-
for (const reason of ["reload", "new"]) {
97-
await shutdown(Object.assign({ systemPrompt: "" }, { reason }), { ui });
98-
await start({ systemPrompt: "" }, { ui });
99-
}
100-
assert.deepStrictEqual(statuses, [
101-
[PI_T3_SESSION_END_STATUS_KEY, "reload"],
102-
["t3:session-start", "started"],
103-
[PI_T3_SESSION_END_STATUS_KEY, "new"],
104-
["t3:session-start", "started"],
105-
]);
106-
},
107-
);
86+
type LifecycleHook = (
87+
event: { systemPrompt: string; reason?: string },
88+
ctx: { ui: { notify: () => void; setStatus: (key: string, text?: string) => void } },
89+
) => unknown;
90+
91+
async function loadLifecycleHooks() {
92+
const handlers = new Map<string, LifecycleHook>();
93+
const source = NodeModule.stripTypeScriptTypes(
94+
PI_T3_LIFECYCLE_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
95+
"export default function",
96+
"function",
97+
),
98+
);
99+
NodeVM.runInNewContext(`${source}\nt3LifecycleExtension(pi)`, {
100+
pi: { on: (name: string, handler: LifecycleHook) => handlers.set(name, handler) },
101+
});
102+
return handlers;
103+
}
104+
105+
it("marks shutdown and replacement start from the lifecycle sentinel only", async () => {
106+
const statuses: Array<readonly [string, string | undefined]> = [];
107+
const ui = {
108+
notify: () => undefined,
109+
setStatus: (key: string, text: string | undefined) => statuses.push([key, text]),
110+
};
111+
const sentinel = await loadLifecycleHooks();
112+
for (const reason of ["reload", "new"]) {
113+
await sentinel.get("session_shutdown")!(Object.assign({ systemPrompt: "" }, { reason }), {
114+
ui,
115+
});
116+
await sentinel.get("session_start")!({ systemPrompt: "" }, { ui });
117+
}
118+
assert.deepStrictEqual(statuses, [
119+
[PI_T3_SESSION_END_STATUS_KEY, "reload"],
120+
[PI_T3_SESSION_START_STATUS_KEY, "started"],
121+
[PI_T3_SESSION_END_STATUS_KEY, "new"],
122+
[PI_T3_SESSION_START_STATUS_KEY, "started"],
123+
]);
124+
125+
// The bridge loads after user extensions; a marker from it would arrive
126+
// after their new background work.
127+
statuses.length = 0;
128+
for (const handlers of [(await loadMcpBridge()).handlers, await loadHooks()]) {
129+
await (handlers.get("session_shutdown") as LifecycleHook | undefined)?.(
130+
Object.assign({ systemPrompt: "" }, { reason: "new" }),
131+
{ ui },
132+
);
133+
await (handlers.get("session_start") as LifecycleHook | undefined)?.(
134+
{ systemPrompt: "" },
135+
{
136+
ui,
137+
},
138+
);
139+
}
140+
assert.deepStrictEqual(statuses, []);
141+
});
108142
});
109143

110144
describe("Pi MCP tool results", () => {

‎packages/provider-pi/src/server/mcpExtensionSource.ts‎

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "@t3tools/provider-core/server/orchestrationInstructions";
66

77
export const PI_T3_MCP_EXTENSION_FILENAME = "pi-t3-mcp-extension.ts";
8+
export const PI_T3_LIFECYCLE_EXTENSION_FILENAME = "pi-t3-lifecycle-extension.ts";
89

910
export const T3_MCP_URL_ENV = "T3_MCP_URL";
1011
export const T3_MCP_BEARER_ENV = "T3_MCP_BEARER_TOKEN";
@@ -24,6 +25,24 @@ export const PI_FILE_CHANGE_TOOLS = ["edit", "write"] as const;
2425
export const PI_T3_SESSION_END_STATUS_KEY = "t3:session-end";
2526
export const PI_T3_SESSION_START_STATUS_KEY = "t3:session-start";
2627

28+
/**
29+
* Pi runs lifecycle hooks in extension order, so this loads before user
30+
* extensions: the start marker must precede their new background work, while
31+
* the MCP and permission bridge keeps its later registration position.
32+
*/
33+
export const PI_T3_LIFECYCLE_EXTENSION_SOURCE = `\
34+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
35+
36+
export default function t3LifecycleExtension(pi: ExtensionAPI) {
37+
pi.on("session_shutdown", (event, ctx) => {
38+
ctx.ui.setStatus(${JSON.stringify(PI_T3_SESSION_END_STATUS_KEY)}, event.reason ?? "ended");
39+
});
40+
pi.on("session_start", (_event, ctx) => {
41+
ctx.ui.setStatus(${JSON.stringify(PI_T3_SESSION_START_STATUS_KEY)}, "started");
42+
});
43+
}
44+
`;
45+
2746
export const PI_T3_MCP_EXTENSION_SOURCE = `\
2847
import { stripFrontmatter, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2948
import * as NodeFSP from "node:fs/promises";
@@ -38,8 +57,6 @@ const ORCHESTRATION_INSTRUCTIONS = ${JSON.stringify(T3_CODE_ORCHESTRATION_INSTRU
3857
const PROTOCOL = "2025-06-18";
3958
const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
4059
const FILE_CHANGE_TOOLS = new Set(${JSON.stringify(PI_FILE_CHANGE_TOOLS)});
41-
const SESSION_END_STATUS_KEY = ${JSON.stringify(PI_T3_SESSION_END_STATUS_KEY)};
42-
const SESSION_START_STATUS_KEY = ${JSON.stringify(PI_T3_SESSION_START_STATUS_KEY)};
4360
4461
type RuntimeMode = "approval-required" | "auto-accept-edits" | "auto" | "full-access";
4562
@@ -348,17 +365,10 @@ export default async function t3McpExtension(pi: ExtensionAPI) {
348365
}
349366
});
350367
351-
// Later shutdown handlers can await cleanup while their contexts still work.
352-
// The adapter ignores their progress until the next session_start marker.
353-
pi.on("session_shutdown", (event, ctx) => {
354-
ctx.ui.setStatus(SESSION_END_STATUS_KEY, event.reason ?? "ended");
355-
});
356-
357368
const endpoint = env(URL_ENV);
358369
const token = env(TOKEN_ENV);
359370
if (endpoint === undefined || token === undefined) {
360371
pi.on("session_start", async (_event, ctx) => {
361-
ctx.ui.setStatus(SESSION_START_STATUS_KEY, "started");
362372
ctx.ui.notify(
363373
"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.",
364374
"warning",
@@ -461,7 +471,6 @@ export default async function t3McpExtension(pi: ExtensionAPI) {
461471
pi.on("session_tree", (_event, ctx) => reconcileDiscovery(ctx));
462472
pi.on("model_select", (_event, ctx) => reconcileDiscovery(ctx));
463473
pi.on("session_start", async (_event, ctx) => {
464-
ctx.ui.setStatus(SESSION_START_STATUS_KEY, "started");
465474
reconcileDiscovery(ctx);
466475
try {
467476
await ensureStarted();

‎packages/provider-pi/src/server/mcpInjection.test.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,14 @@ describe("pi T3 MCP injection", () => {
3333
environment: { PATH: "/usr/bin" },
3434
mcpSession,
3535
extensionPath: "/tmp/cache/pi-t3-mcp-extension.ts",
36+
lifecycleExtensionPath: "/tmp/cache/pi-t3-lifecycle-extension.ts",
3637
runtimeMode: "approval-required",
3738
});
3839
assert.deepEqual(launch.args, [
3940
"--mode",
4041
"rpc",
4142
"--extension",
42-
"/tmp/cache/pi-t3-mcp-extension.ts",
43+
"/tmp/cache/pi-t3-lifecycle-extension.ts",
4344
"--extension",
4445
"/home/user/.pi/agent/extensions/demo.ts",
4546
"--session-dir",
@@ -53,6 +54,8 @@ describe("pi T3 MCP injection", () => {
5354
"--name",
5455
"-review",
5556
"--extension-flag=kept",
57+
"--extension",
58+
"/tmp/cache/pi-t3-mcp-extension.ts",
5659
]);
5760
assert.notInclude(launch.args, "--no-extensions");
5861
assert.equal(launch.env[T3_MCP_URL_ENV], "http://127.0.0.1:43123/mcp");
@@ -69,12 +72,15 @@ describe("pi T3 MCP injection", () => {
6972
},
7073
mcpSession: undefined,
7174
extensionPath: "/tmp/cache/pi-t3-mcp-extension.ts",
75+
lifecycleExtensionPath: "/tmp/cache/pi-t3-lifecycle-extension.ts",
7276
runtimeMode: "auto-accept-edits",
7377
});
7478
assert.deepEqual(permissionOnly.args, [
7579
"--mode",
7680
"rpc",
7781
"--extension",
82+
"/tmp/cache/pi-t3-lifecycle-extension.ts",
83+
"--extension",
7884
"/tmp/cache/pi-t3-mcp-extension.ts",
7985
]);
8086
assert.isFalse(permissionOnly.hasT3Mcp);
@@ -87,18 +93,24 @@ describe("pi T3 MCP injection", () => {
8793
);
8894
});
8995

90-
it("loads the lifecycle bridge first when it is also in user launch args", () => {
96+
it("loads only the lifecycle markers ahead of user extensions", () => {
9197
const bridge = "/tmp/cache/pi-t3-mcp-extension.ts";
98+
const lifecycle = "/tmp/cache/pi-t3-lifecycle-extension.ts";
9299
const launch = buildPiRpcLaunch({
93-
launchArgs: ["-e", "/user/extension.ts", "--extension", bridge],
100+
launchArgs: ["-e", bridge, "-e", "/user/extension.ts"],
94101
environment: {},
95102
mcpSession: undefined,
96103
extensionPath: bridge,
104+
lifecycleExtensionPath: lifecycle,
97105
});
106+
// The bridge keeps the user's chosen position, so tool and permission
107+
// registration order is unchanged by the lifecycle sentinel.
98108
assert.deepEqual(launch.args, [
99109
"--mode",
100110
"rpc",
101111
"--extension",
112+
lifecycle,
113+
"-e",
102114
bridge,
103115
"-e",
104116
"/user/extension.ts",

0 commit comments

Comments
 (0)