Skip to content

Commit 645746b

Browse files
committed
fix(server): Pi loads every selected skill without losing prompt text
1 parent a4c9494 commit 645746b

6 files changed

Lines changed: 168 additions & 155 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/PiAdapterV2.test.ts‎

Lines changed: 2 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,6 @@ interface FakePi {
9595
readonly allRequests: () => ReadonlyArray<PiRpcRecord>;
9696
/** Data returned by the next `get_session_stats` acks, consumed in order. */
9797
readonly queueStats: (data: unknown) => void;
98-
/** Data returned by the next `get_commands` acks, consumed in order. */
99-
readonly queueCommands: (data: unknown) => void;
100-
/** Make the next `get_commands` ack fail. */
101-
readonly failNextCommands: () => void;
10298
/** Close the fake process stdout stream. */
10399
readonly closeStdout: Effect.Effect<void>;
104100
readonly lastSpawn: () => {
@@ -138,7 +134,6 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
138134
const messagesQueue: Array<unknown> = [];
139135
const stateQueue: Array<Record<string, unknown>> = [];
140136
const statsQueue: Array<unknown> = [];
141-
const commandsQueue: Array<{ readonly success: boolean; readonly data?: unknown }> = [];
142137
const allRequests: Array<PiRpcRecord> = [];
143138
let deferState = false;
144139
let deferredStateRequest: PiRpcRecord | undefined;
@@ -192,8 +187,6 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
192187
return { ...base, data: messagesQueue.shift() ?? { messages: [] } };
193188
case "get_session_stats":
194189
return { ...base, data: statsQueue.shift() ?? {} };
195-
case "get_commands":
196-
return { ...base, ...(commandsQueue.shift() ?? { data: { commands: [] } }) };
197190
case "fork":
198191
return { ...base, data: { text: "Hello pi", cancelled: false } };
199192
default:
@@ -303,8 +296,6 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
303296
},
304297
queueState: (data) => stateQueue.push(data),
305298
queueStats: (data) => statsQueue.push(data),
306-
queueCommands: (data) => commandsQueue.push({ success: true, data }),
307-
failNextCommands: () => commandsQueue.push({ success: false }),
308299
closeStdout: Queue.end(stdout),
309300
lastSpawn: () => lastSpawn,
310301
} satisfies FakePi;
@@ -912,22 +903,9 @@ describe("PiAdapterV2", () => {
912903
}).pipe(Effect.scoped, Effect.provide(layerTest)),
913904
);
914905

915-
it.effect("expands a selected $ skill through Pi's native skill command", () =>
906+
it.effect("preserves selected skill references for the Pi extension to expand", () =>
916907
Effect.gen(function* () {
917908
const fake = yield* makeFakePi;
918-
fake.queueCommands({
919-
commands: [
920-
{
921-
name: "skill:repo-review",
922-
description: "Review this repository.",
923-
source: "skill",
924-
sourceInfo: {
925-
path: "/workspace/.agents/skills/repo-review/SKILL.md",
926-
scope: "project",
927-
},
928-
},
929-
],
930-
});
931909
const { runtime } = yield* openRuntime(fake);
932910
const providerThread = yield* runtime.ensureThread({
933911
threadId: THREAD_ID,
@@ -943,43 +921,7 @@ describe("PiAdapterV2", () => {
943921
"Review this change please $repo-review",
944922
);
945923
const prompt = yield* fake.takeRequest("prompt");
946-
assert.equal(prompt["message"], "/skill:repo-review Review this change please");
947-
}).pipe(Effect.scoped, Effect.provide(layerTest)),
948-
);
949-
950-
it.effect("expands every selected $ skill through Pi native skill commands", () =>
951-
Effect.gen(function* () {
952-
const fake = yield* makeFakePi;
953-
fake.queueCommands({
954-
commands: [
955-
{
956-
name: "skill:repo-review",
957-
source: "skill",
958-
sourceInfo: {
959-
path: "/workspace/.agents/skills/repo-review/SKILL.md",
960-
scope: "project",
961-
},
962-
},
963-
{
964-
name: "skill:deploy",
965-
source: "skill",
966-
sourceInfo: {
967-
path: "/workspace/.agents/skills/deploy/SKILL.md",
968-
scope: "project",
969-
},
970-
},
971-
],
972-
});
973-
const { runtime } = yield* openRuntime(fake);
974-
const providerThread = yield* runtime.ensureThread({
975-
threadId: THREAD_ID,
976-
modelSelection: modelSelection("default"),
977-
runtimePolicy,
978-
});
979-
980-
yield* startTurn(runtime, providerThread, "default", [], "use $repo-review and $deploy");
981-
const prompt = yield* fake.takeRequest("prompt");
982-
assert.equal(prompt["message"], "/skill:repo-review /skill:deploy use and");
924+
assert.equal(prompt["message"], "Review this change please $repo-review");
983925
}).pipe(Effect.scoped, Effect.provide(layerTest)),
984926
);
985927

‎apps/server/src/orchestration-v2/Adapters/PiAdapterV2.ts‎

Lines changed: 2 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,7 @@ import { resolveAttachmentPath } from "../../attachmentStore.ts";
6363
import * as ServerConfig from "../../config.ts";
6464
import { mcpToolPresentation } from "../../provider/McpToolPresentation.ts";
6565
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
66-
import {
67-
expandPiSkillReference,
68-
parsePiCompactCommand,
69-
parsePiDiscoveredCommands,
70-
type PiCompactCommand,
71-
} from "../../provider/PiCommands.ts";
66+
import { parsePiCompactCommand, type PiCompactCommand } from "../../provider/PiCommands.ts";
7267
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
7368
import * as IdAllocator from "../IdAllocator.ts";
7469
import * as ProviderAdapter from "../ProviderAdapter.ts";
@@ -110,7 +105,6 @@ const STREAM_FLUSH_MS = 50;
110105
const PI_REQUEST_TIMEOUT_MS = 15_000;
111106
// Session lifecycle hooks reload extensions, MCP servers and language servers.
112107
const PI_SESSION_TIMEOUT_MS = 60_000;
113-
const PI_SKILL_DISCOVERY_TIMEOUT_MS = 4_000;
114108
const PI_UNSOLICITED_ACTIVITY_ERROR =
115109
"Pi started agent work outside an active T3 turn. The session was stopped to prevent invisible tool execution.";
116110
const SETTLE_PROBE_MAX_ATTEMPTS = 3;
@@ -436,15 +430,6 @@ export function makePiAdapterV2(
436430
}),
437431
),
438432
);
439-
const discoverSkillNames = connection
440-
.request({ type: "get_commands" }, PI_SKILL_DISCOVERY_TIMEOUT_MS)
441-
.pipe(
442-
Effect.map(
443-
(data) => new Set(parsePiDiscoveredCommands(data).skills.map((skill) => skill.name)),
444-
),
445-
);
446-
let skillNames: Set<string> | null = null;
447-
448433
const now = yield* DateTime.now;
449434
let sessionEntity: OrchestrationV2ProviderSession = {
450435
id: input.providerSessionId,
@@ -1983,16 +1968,6 @@ export function makePiAdapterV2(
19831968
Effect.forkIn(scope),
19841969
);
19851970

1986-
// Discovery can invoke extension code and therefore raise a blocking
1987-
// UI request. Start it only after the event pump exists, and never hold
1988-
// session opening on it; startup requests are persisted at session
1989-
// scope and can be answered before a turn begins.
1990-
yield* discoverSkillNames.pipe(
1991-
Effect.tap((discovered) => Effect.sync(() => (skillNames = discovered))),
1992-
Effect.ignore,
1993-
Effect.forkIn(scope),
1994-
);
1995-
19961971
// ── session runtime ───────────────────────────────────
19971972

19981973
const registerThread = Effect.fnUntraced(function* (
@@ -2178,15 +2153,6 @@ export function makePiAdapterV2(
21782153
text: string,
21792154
attachments: ReadonlyArray<ChatAttachment>,
21802155
) {
2181-
// Provider discovery and the live session are separate Pi processes.
2182-
// Retry a failed session-local lookup once at first use so a transient
2183-
// startup failure cannot leave a visible $ skill inert for this session.
2184-
if (skillNames === null && text.includes("$")) {
2185-
skillNames = yield* discoverSkillNames.pipe(
2186-
Effect.orElseSucceed(() => new Set<string>()),
2187-
);
2188-
}
2189-
const expandedText = skillNames === null ? text : expandPiSkillReference(text, skillNames);
21902156
const images: Array<{ type: "image"; data: string; mimeType: string }> = [];
21912157
const extraLines: Array<string> = [];
21922158
for (const attachment of attachments) {
@@ -2206,8 +2172,7 @@ export function makePiAdapterV2(
22062172
extraLines.push(`[Attachment saved at ${path}]`);
22072173
}
22082174
}
2209-
const message =
2210-
extraLines.length === 0 ? expandedText : `${expandedText}\n\n${extraLines.join("\n")}`;
2175+
const message = extraLines.length === 0 ? text : `${text}\n\n${extraLines.join("\n")}`;
22112176
return { message, images };
22122177
});
22132178

‎apps/server/src/orchestration-v2/Adapters/piT3McpExtensionSource.test.ts‎

Lines changed: 129 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- Pi extensions run outside Effect; these tests exercise their native filesystem boundary.
12
import * as NodeModule from "node:module";
23
import * as NodeVM from "node:vm";
4+
import * as NodeFSP from "node:fs/promises";
5+
import * as NodePath from "node:path";
6+
import * as NodeOS from "node:os";
37
import { assert, describe, it } from "@effect/vitest";
48

59
import { PI_T3_MCP_EXTENSION_SOURCE } from "./piT3McpExtensionSource.ts";
@@ -9,22 +13,52 @@ type RequestHook = (
913
ctx: { model: { provider: string } },
1014
) => Record<string, unknown> | undefined;
1115

12-
async function loadRequestHook(): Promise<RequestHook> {
13-
const handlers = new Map<string, RequestHook>();
16+
interface SkillCommand {
17+
readonly name: string;
18+
readonly source: string;
19+
readonly sourceInfo: { readonly path: string };
20+
}
21+
22+
type InputHook = (
23+
event: { text: string; images?: ReadonlyArray<unknown> },
24+
ctx: { ui: { notify: (message: string, level: string) => void } },
25+
) => Promise<{ action: string; text: string; images?: ReadonlyArray<unknown> } | undefined>;
26+
27+
async function loadHooks(commands: ReadonlyArray<SkillCommand> = []) {
28+
const handlers = new Map<string, unknown>();
1429
// Execute the shipped extension with MCP disabled; this path needs no Typebox.
1530
const source = NodeModule.stripTypeScriptTypes(
16-
PI_T3_MCP_EXTENSION_SOURCE.replace('import { Type } from "typebox";', "").replace(
31+
PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
1732
"export default async function",
1833
"async function",
1934
),
2035
);
2136
await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
2237
process: { env: {} },
23-
pi: { on: (name: string, handler: RequestHook) => handlers.set(name, handler) },
38+
NodeFSP,
39+
NodePath,
40+
// Frontmatter parsing belongs to Pi. These fixtures contain only skill bodies.
41+
stripFrontmatter: (content: string) => content,
42+
pi: {
43+
on: (name: string, handler: unknown) => handlers.set(name, handler),
44+
getCommands: () => commands,
45+
},
2446
});
47+
return handlers;
48+
}
49+
50+
async function loadRequestHook(): Promise<RequestHook> {
51+
const handlers = await loadHooks();
2552
const hook = handlers.get("before_provider_request");
2653
assert.isDefined(hook);
27-
return hook!;
54+
return hook as RequestHook;
55+
}
56+
57+
async function loadInputHook(commands: ReadonlyArray<SkillCommand>) {
58+
const handlers = await loadHooks(commands);
59+
const hook = handlers.get("input");
60+
assert.isDefined(hook);
61+
return hook as InputHook;
2862
}
2963

3064
describe("Pi upstream output-budget workaround", () => {
@@ -57,3 +91,93 @@ describe("Pi upstream output-budget workaround", () => {
5791
);
5892
});
5993
});
94+
95+
describe("Pi skill references", () => {
96+
it("loads every selected skill once while preserving inline prose, whitespace, and images", async () => {
97+
const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
98+
try {
99+
const alpha = NodePath.join(directory, "alpha.md");
100+
const beta = NodePath.join(directory, "beta.md");
101+
await NodeFSP.writeFile(alpha, "ALPHA_INSTRUCTIONS");
102+
await NodeFSP.writeFile(beta, "BETA_INSTRUCTIONS");
103+
const hook = await loadInputHook([
104+
{ name: "skill:alpha", source: "skill", sourceInfo: { path: alpha } },
105+
{ name: "skill:beta", source: "skill", sourceInfo: { path: beta } },
106+
]);
107+
const text =
108+
"Please use the $alpha philosophy, then $beta and $alpha\n```ts\n const x = 1;\n```";
109+
const images = [{ type: "image", data: "fixture" }];
110+
const result = await hook({ text, images }, { ui: { notify: assert.fail } });
111+
assert.equal(result?.action, "transform");
112+
assert.isTrue(result?.text.startsWith(text + "\n\n"));
113+
assert.equal(result?.text.split("ALPHA_INSTRUCTIONS").length, 2);
114+
assert.equal(result?.text.split("BETA_INSTRUCTIONS").length, 2);
115+
assert.include(result?.text ?? "", `References are relative to ${directory}.`);
116+
assert.strictEqual(result?.images, images);
117+
} finally {
118+
await NodeFSP.rm(directory, { recursive: true });
119+
}
120+
});
121+
122+
it("leaves unknown references and native skill commands for Pi", async () => {
123+
const hook = await loadInputHook([
124+
{ name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
125+
]);
126+
for (const text of ["Explain $HOME", "/skill:alpha use $alpha", "Hello", "$missing"]) {
127+
assert.isUndefined(await hook({ text }, { ui: { notify: assert.fail } }));
128+
}
129+
});
130+
131+
it("loads additional chips without duplicating a leading native skill", async () => {
132+
const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
133+
try {
134+
const path = NodePath.join(directory, "beta.md");
135+
await NodeFSP.writeFile(path, "BETA_INSTRUCTIONS");
136+
const hook = await loadInputHook([
137+
{ name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
138+
{ name: "skill:beta", source: "skill", sourceInfo: { path } },
139+
]);
140+
const text = "/skill:alpha use $alpha and $beta";
141+
const result = await hook({ text }, { ui: { notify: assert.fail } });
142+
assert.isTrue(result?.text.startsWith(text + "\n\n"));
143+
assert.notInclude(result?.text ?? "", '<skill name="alpha"');
144+
assert.include(result?.text ?? "", "BETA_INSTRUCTIONS");
145+
} finally {
146+
await NodeFSP.rm(directory, { recursive: true });
147+
}
148+
});
149+
150+
it("reports an unreadable skill without deleting its reference or other selected instructions", async () => {
151+
const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
152+
try {
153+
const path = NodePath.join(directory, "readable.md");
154+
await NodeFSP.writeFile(path, "READABLE_INSTRUCTIONS");
155+
const hook = await loadInputHook([
156+
{
157+
name: "skill:missing",
158+
source: "skill",
159+
sourceInfo: { path: NodePath.join(directory, "missing.md") },
160+
},
161+
{ name: "skill:readable", source: "skill", sourceInfo: { path } },
162+
]);
163+
const notices: string[] = [];
164+
const text = "Use $missing and $readable";
165+
const result = await hook(
166+
{ text },
167+
{
168+
ui: {
169+
notify: (message) => {
170+
notices.push(message);
171+
},
172+
},
173+
},
174+
);
175+
assert.isTrue(result?.text.startsWith(text + "\n\n"));
176+
assert.include(result?.text ?? "", "READABLE_INSTRUCTIONS");
177+
assert.equal(notices.length, 1);
178+
assert.include(notices[0] ?? "", "Could not load skill missing");
179+
} finally {
180+
await NodeFSP.rm(directory, { recursive: true });
181+
}
182+
});
183+
});

‎apps/server/src/orchestration-v2/Adapters/piT3McpExtensionSource.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ export const T3_PI_RUNTIME_MODE_ENV = "T3_PI_RUNTIME_MODE";
2323
export const PI_FILE_CHANGE_TOOLS = ["edit", "write"] as const;
2424

2525
export const PI_T3_MCP_EXTENSION_SOURCE = `\
26-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
26+
import { stripFrontmatter, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
27+
import * as NodeFSP from "node:fs/promises";
28+
import * as NodePath from "node:path";
2729
import { Type } from "typebox";
2830
2931
const URL_ENV = ${JSON.stringify(T3_MCP_URL_ENV)};
@@ -210,6 +212,38 @@ function createMcpClient(endpoint: string, token: string) {
210212
}
211213
212214
export default async function t3McpExtension(pi: ExtensionAPI) {
215+
// Keep skill chips in the request. Pi expands only one leading /skill:
216+
// command, so use its own frontmatter loader for every selected chip here.
217+
pi.on("input", async (event, ctx) => {
218+
if (!event.text.includes("$")) return;
219+
const commands = pi.getCommands().filter((command) => command.source === "skill");
220+
const nativeSkill = /^\\/skill:([^ ]+)(?: |$)/.exec(event.text)?.[1];
221+
const seen = new Set<string>(nativeSkill === undefined ? [] : [nativeSkill]);
222+
const blocks: string[] = [];
223+
for (const match of event.text.matchAll(/(^|\\s)\\$([^\\s]+)(?=\\s|$)/g)) {
224+
const name = match[2];
225+
if (name === undefined || seen.has(name)) continue;
226+
const command = commands.find((candidate) => candidate.name === "skill:" + name);
227+
if (command === undefined) continue;
228+
seen.add(name);
229+
const path = command.sourceInfo.path;
230+
try {
231+
const body = stripFrontmatter(await NodeFSP.readFile(path, "utf8")).trim();
232+
blocks.push(
233+
\`<skill name="\${name}" location="\${path}">\\nReferences are relative to \${NodePath.dirname(path)}.\\n\\n\${body}\\n</skill>\`,
234+
);
235+
} catch {
236+
ctx.ui.notify(\`Could not load skill \${name} from \${path}.\`, "error");
237+
}
238+
}
239+
if (blocks.length === 0) return;
240+
return {
241+
action: "transform",
242+
text: event.text + "\\n\\n" + blocks.join("\\n\\n"),
243+
images: event.images,
244+
};
245+
});
246+
213247
// Workaround for an upstream Pi context-budgeting bug: pi-ai reuses the
214248
// previous response's usage even when a fork's instructions/tools differ,
215249
// then reserves almost all remaining context for output. OpenRouter can

0 commit comments

Comments
 (0)