1
import { existsSync, mkdirSync, rmSync } from "node:fs";2
import { tmpdir } from "node:os";3
import { join } from "node:path";4
import { Agent } from "@earendil-works/pi-agent-core";5
import {6
type AssistantMessage,7
createAssistantMessageEventStream,8
getModel,9
type Model,10
} from "@earendil-works/pi-ai/compat";11
import { afterEach, describe, expect, it, vi } from "vitest";12
import { AgentSession } from "../src/core/agent-session.ts";13
import type { AgentSessionRuntime } from "../src/core/agent-session-runtime.ts";14
import { AuthStorage } from "../src/core/auth-storage.ts";15
import type { LoadExtensionsResult } from "../src/core/extensions/index.ts";16
import { SessionManager } from "../src/core/session-manager.ts";17
import { SettingsManager } from "../src/core/settings-manager.ts";18
import { runRpcMode } from "../src/modes/rpc/rpc-mode.ts";19
import { createInMemoryModelRegistry, getModelRuntime } from "./model-runtime-test-utils.ts";20
import { createTestExtensionsResult, createTestResourceLoader } from "./utilities.ts";22
const rpcIo = vi.hoisted(() => ({23
outputLines: [] as string[],24
lineHandler: undefined as ((line: string) => void) | undefined,25
}));27
vi.mock("../src/core/output-guard.js", () => ({28
flushRawStdout: vi.fn(async () => {}),29
takeOverStdout: vi.fn(),30
waitForRawStdoutBackpressure: vi.fn(async () => {}),31
writeRawStdout: (line: string) => {32
rpcIo.outputLines.push(line);33
},34
}));36
vi.mock("../src/modes/interactive/theme/theme.js", () => ({ theme: {} }));38
vi.mock("../src/modes/rpc/jsonl.js", () => ({39
attachJsonlLineReader: vi.fn((_stream: NodeJS.ReadableStream, onLine: (line: string) => void) => {40
rpcIo.lineHandler = onLine;41
return () => {};42
}),43
serializeJsonLine: (value: unknown) => `${JSON.stringify(value)}\n`,44
}));46
function createAssistantMessage(text: string): AssistantMessage {47
return {48
role: "assistant",49
content: [{ type: "text", text }],50
api: "anthropic-messages",51
provider: "anthropic",52
model: "claude-sonnet-4-5",53
usage: {54
input: 0,55
output: 0,56
cacheRead: 0,57
cacheWrite: 0,58
totalTokens: 0,59
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },60
},61
stopReason: "stop",62
timestamp: Date.now(),63
};64
}66
type ParsedOutputLine = Record<string, unknown>;68
function parseOutputLines(outputLines: string[]): ParsedOutputLine[] {69
return outputLines70
.flatMap((line) => line.split("\n"))71
.filter((line) => line.trim().length > 0)72
.map((line) => JSON.parse(line) as ParsedOutputLine);73
}75
function getPromptResponses(outputLines: string[], id: string): ParsedOutputLine[] {76
return parseOutputLines(outputLines).filter(77
(record) => record.id === id && record.type === "response" && record.command === "prompt",78
);79
}81
function sleep(ms: number): Promise<void> {82
return new Promise((resolve) => setTimeout(resolve, ms));83
}85
async function createRuntimeHost(options: {86
withAuth: boolean;87
responseDelayMs: number;88
model?: Model<any>;89
extensionsResult?: LoadExtensionsResult;90
}): Promise<{91
runtimeHost: AgentSessionRuntime;92
cleanup: () => Promise<void>;93
}> {94
const tempDir = join(tmpdir(), `pi-rpc-prompt-${Date.now()}-${Math.random().toString(36).slice(2)}`);95
mkdirSync(tempDir, { recursive: true });97
const model = options.model ?? getModel("anthropic", "claude-sonnet-4-5");98
if (!model) {99
throw new Error("Test model not found");100
}102
const agent = new Agent({103
getApiKey: () => "test-key",104
initialState: {105
model,106
systemPrompt: "Test",107
tools: [],108
},109
streamFn: (_model, _context, _options) => {110
const stream = createAssistantMessageEventStream();111
queueMicrotask(() => {112
stream.push({ type: "start", partial: createAssistantMessage("") });113
setTimeout(() => {114
stream.push({ type: "done", reason: "stop", message: createAssistantMessage("done") });115
}, options.responseDelayMs);116
});117
return stream;118
},119
});121
const sessionManager = SessionManager.inMemory();122
const settingsManager = SettingsManager.create(tempDir, tempDir);123
const authStorage = AuthStorage.create(join(tempDir, "auth.json"));124
const modelRegistry = await createInMemoryModelRegistry(authStorage);125
if (options.withAuth) {126
await authStorage.modify("anthropic", async () => ({ type: "api_key", key: "test-key" }));127
}129
const session = new AgentSession({130
agent,131
sessionManager,132
settingsManager,133
cwd: tempDir,134
modelRuntime: getModelRuntime(modelRegistry),135
resourceLoader: createTestResourceLoader({ extensionsResult: options.extensionsResult }),136
});138
const runtimeHost = {139
session,140
newSession: vi.fn(async () => ({ cancelled: true })),141
switchSession: vi.fn(async () => ({ cancelled: true })),142
fork: vi.fn(async () => ({ cancelled: true, selectedText: "" })),143
dispose: vi.fn(async () => {}),144
setRebindSession: vi.fn(),145
} as unknown as AgentSessionRuntime;147
return {148
runtimeHost,149
cleanup: async () => {150
try {151
await session.abort();152
} catch {153
// ignore test cleanup failures154
}155
session.dispose();156
if (existsSync(tempDir)) {157
rmSync(tempDir, { recursive: true });158
}159
},160
};161
}163
async function startRpcMode(options: Parameters<typeof createRuntimeHost>[0]): Promise<{164
lineHandler: (line: string) => void;165
cleanup: () => Promise<void>;166
}> {167
rpcIo.outputLines = [];168
rpcIo.lineHandler = undefined;170
const { runtimeHost, cleanup } = await createRuntimeHost(options);171
void runRpcMode(runtimeHost);172
await vi.waitFor(() => expect(rpcIo.lineHandler).toBeDefined());174
return { lineHandler: rpcIo.lineHandler!, cleanup };175
}177
describe("RPC prompt response semantics", () => {178
afterEach(() => {179
rpcIo.outputLines = [];180
rpcIo.lineHandler = undefined;181
});183
it("emits one failure response when prompt preflight rejects", async () => {184
const { lineHandler, cleanup } = await startRpcMode({185
withAuth: false,186
responseDelayMs: 0,187
model: {188
id: "fake-model",189
name: "Fake Model",190
api: "openai-completions",191
provider: "fake-provider",192
baseUrl: "https://example.invalid",193
reasoning: false,194
input: [],195
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },196
contextWindow: 0,197
maxTokens: 0,198
},199
});201
try {202
lineHandler(JSON.stringify({ id: "b1", type: "prompt", message: "Hello" }));204
await vi.waitFor(() => {205
const responses = getPromptResponses(rpcIo.outputLines, "b1");206
expect(responses).toHaveLength(1);207
expect(responses[0]).toMatchObject({208
id: "b1",209
type: "response",210
command: "prompt",211
success: false,212
error: expect.stringContaining(213
"No API key found for fake-provider.\n\nUse /login to log into a provider via OAuth or API key. See:",214
),215
});216
});217
} finally {218
await cleanup();219
}220
});222
// #9098: a successful prompt may start an agent run or be consumed by an extension.223
it("emits one started response when prompt preflight succeeds", async () => {224
const { lineHandler, cleanup } = await startRpcMode({ withAuth: true, responseDelayMs: 0 });226
try {227
lineHandler(JSON.stringify({ id: "b2", type: "prompt", message: "Hello" }));229
await vi.waitFor(() => {230
const responses = getPromptResponses(rpcIo.outputLines, "b2");231
expect(responses).toHaveLength(1);232
expect(responses[0]).toMatchObject({233
id: "b2",234
type: "response",235
command: "prompt",236
success: true,237
data: { disposition: "started" },238
});239
});240
} finally {241
await cleanup();242
}243
});245
it("reports extension commands and intercepted input as handled without starting a run", async () => {246
const { lineHandler, cleanup } = await startRpcMode({247
withAuth: false,248
responseDelayMs: 0,249
extensionsResult: await createTestExtensionsResult([250
(pi) => {251
pi.registerCommand("handled", { handler: async () => {} });252
pi.on("input", (event) => {253
if (event.text === "handled input") return { action: "handled" };254
});255
},256
]),257
});259
try {260
for (const [id, message] of [261
["command", "/handled"],262
["input", "handled input"],263
]) {264
lineHandler(JSON.stringify({ id, type: "prompt", message }));265
await vi.waitFor(() => {266
expect(getPromptResponses(rpcIo.outputLines, id)).toEqual([267
{ id, type: "response", command: "prompt", success: true, data: { disposition: "handled" } },268
]);269
});270
}271
expect(parseOutputLines(rpcIo.outputLines).filter((line) => line.type === "agent_start")).toHaveLength(0);272
} finally {273
await cleanup();274
}275
});277
it("emits one success response when prompt is queued during streaming", async () => {278
const { lineHandler, cleanup } = await startRpcMode({ withAuth: true, responseDelayMs: 100 });280
try {281
lineHandler(JSON.stringify({ id: "b3-start", type: "prompt", message: "Start" }));282
await vi.waitFor(() => {283
expect(getPromptResponses(rpcIo.outputLines, "b3-start")).toHaveLength(1);284
});286
rpcIo.outputLines = [];287
lineHandler(288
JSON.stringify({289
id: "b3",290
type: "prompt",291
message: "Queue this",292
streamingBehavior: "followUp",293
}),294
);296
await vi.waitFor(() => {297
const responses = getPromptResponses(rpcIo.outputLines, "b3");298
expect(responses).toHaveLength(1);299
expect(responses[0]).toMatchObject({300
id: "b3",301
type: "response",302
command: "prompt",303
success: true,304
data: { disposition: "queued" },305
});306
});308
await sleep(150);309
} finally {310
await cleanup();311
}312
});314
// #9803: a handler can consume A while independently queueing B; report A's outcome.315
it.each(["steer", "follow_up"] as const)(316
"reports %s as handled even when an extension queues another message",317
async (type) => {318
const { lineHandler, cleanup } = await startRpcMode({319
withAuth: true,320
responseDelayMs: 500,321
extensionsResult: await createTestExtensionsResult([322
(pi) => {323
pi.on("input", (event) => {324
if (event.text === "A" && event.source === "rpc") {325
pi.sendUserMessage("B", { deliverAs: type === "steer" ? "steer" : "followUp" });326
return { action: "handled" };327
}328
});329
},330
]),331
});333
try {334
lineHandler(JSON.stringify({ id: "start", type: "prompt", message: "Start" }));335
await vi.waitFor(() => expect(getPromptResponses(rpcIo.outputLines, "start")).toHaveLength(1));337
lineHandler(JSON.stringify({ id: "A", type, message: "A" }));338
await vi.waitFor(() => {339
expect(parseOutputLines(rpcIo.outputLines)).toContainEqual({340
id: "A",341
type: "response",342
command: type,343
success: true,344
data: { disposition: "handled" },345
});346
expect(parseOutputLines(rpcIo.outputLines)).toContainEqual({347
type: "queue_update",348
steering: type === "steer" ? ["B"] : [],349
followUp: type === "follow_up" ? ["B"] : [],350
});351
});352
await vi.waitFor(() => {353
expect(354
parseOutputLines(rpcIo.outputLines).filter((line) => line.type === "response" && line.id === "A"),355
).toHaveLength(1);356
});357
} finally {358
await cleanup();359
}360
},361
);363
it.each(["steer", "follow_up"] as const)("reports %s as queued after input transformation", async (type) => {364
const { lineHandler, cleanup } = await startRpcMode({365
withAuth: false,366
responseDelayMs: 0,367
extensionsResult: await createTestExtensionsResult([368
(pi) => {369
pi.on("input", (event) => {370
if (event.text === "A") return { action: "transform", text: "B" };371
});372
},373
]),374
});376
try {377
lineHandler(JSON.stringify({ id: "A", type, message: "A" }));378
await vi.waitFor(() => {379
expect(parseOutputLines(rpcIo.outputLines)).toContainEqual({380
id: "A",381
type: "response",382
command: type,383
success: true,384
data: { disposition: "queued" },385
});386
expect(parseOutputLines(rpcIo.outputLines)).toContainEqual({387
type: "queue_update",388
steering: type === "steer" ? ["B"] : [],389
followUp: type === "follow_up" ? ["B"] : [],390
});391
});392
} finally {393
await cleanup();394
}395
});397
it("returns and clears queued steering and follow-up messages", async () => {398
const { lineHandler, cleanup } = await startRpcMode({ withAuth: true, responseDelayMs: 500 });400
try {401
lineHandler(JSON.stringify({ id: "clear-start", type: "prompt", message: "Start" }));402
await vi.waitFor(() => {403
expect(getPromptResponses(rpcIo.outputLines, "clear-start")).toHaveLength(1);404
});406
lineHandler(407
JSON.stringify({408
id: "clear-steering",409
type: "prompt",410
message: "Change direction",411
streamingBehavior: "steer",412
}),413
);414
await vi.waitFor(() => {415
expect(getPromptResponses(rpcIo.outputLines, "clear-steering")).toMatchObject([416
{ data: { disposition: "queued" } },417
]);418
});420
lineHandler(421
JSON.stringify({422
id: "clear-follow-up",423
type: "prompt",424
message: "Summarize when finished",425
streamingBehavior: "followUp",426
}),427
);428
await vi.waitFor(() => {429
expect(getPromptResponses(rpcIo.outputLines, "clear-follow-up")).toHaveLength(1);430
});432
lineHandler(JSON.stringify({ id: "clear", type: "clear_queue" }));433
await vi.waitFor(() => {434
expect(parseOutputLines(rpcIo.outputLines)).toContainEqual({435
id: "clear",436
type: "response",437
command: "clear_queue",438
success: true,439
data: {440
steering: ["Change direction"],441
followUp: ["Summarize when finished"],442
},443
});444
});446
await sleep(600);447
expect(parseOutputLines(rpcIo.outputLines).filter((record) => record.type === "agent_start")).toHaveLength(1);448
} finally {449
await cleanup();450
}451
});452
});