c6fc084534
Breaking changes: - Settings: 'hooks' and 'customTools' arrays replaced with 'extensions' - CLI: '--hook' and '--tool' flags replaced with '--extension' / '-e' - API: HookMessage renamed to CustomMessage, role 'hookMessage' to 'custom' - API: FileSlashCommand renamed to PromptTemplate - API: discoverSlashCommands() renamed to discoverPromptTemplates() - Directories: commands/ renamed to prompts/ for prompt templates Migration: - Session version bumped to 3 (auto-migrates v2 sessions) - Old 'hookMessage' role entries converted to 'custom' Structural changes: - src/core/hooks/ and src/core/custom-tools/ merged into src/core/extensions/ - src/core/slash-commands.ts renamed to src/core/prompt-templates.ts - examples/hooks/ and examples/custom-tools/ merged into examples/extensions/ - docs/hooks.md and docs/custom-tools.md merged into docs/extensions.md New test coverage: - test/extensions-runner.test.ts (10 tests) - test/extensions-discovery.test.ts (26 tests) - test/prompt-templates.test.ts
106 lines
3.2 KiB
TypeScript
106 lines
3.2 KiB
TypeScript
/**
|
|
* Print mode (single-shot): Send prompts, output result, exit.
|
|
*
|
|
* Used for:
|
|
* - `pi -p "prompt"` - text output
|
|
* - `pi --mode json "prompt"` - JSON event stream
|
|
*/
|
|
|
|
import type { AssistantMessage, ImageContent } from "@mariozechner/pi-ai";
|
|
import type { AgentSession } from "../core/agent-session.js";
|
|
|
|
/**
|
|
* Run in print (single-shot) mode.
|
|
* Sends prompts to the agent and outputs the result.
|
|
*
|
|
* @param session The agent session
|
|
* @param mode Output mode: "text" for final response only, "json" for all events
|
|
* @param messages Array of prompts to send
|
|
* @param initialMessage Optional first message (may contain @file content)
|
|
* @param initialImages Optional images for the initial message
|
|
*/
|
|
export async function runPrintMode(
|
|
session: AgentSession,
|
|
mode: "text" | "json",
|
|
messages: string[],
|
|
initialMessage?: string,
|
|
initialImages?: ImageContent[],
|
|
): Promise<void> {
|
|
// Extension runner already has no-op UI context by default (set in loader)
|
|
// Set up extensions for print mode (no UI)
|
|
const extensionRunner = session.extensionRunner;
|
|
if (extensionRunner) {
|
|
extensionRunner.initialize({
|
|
getModel: () => session.model,
|
|
sendMessageHandler: (message, options) => {
|
|
session.sendCustomMessage(message, options).catch((e) => {
|
|
console.error(`Extension sendMessage failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
});
|
|
},
|
|
appendEntryHandler: (customType, data) => {
|
|
session.sessionManager.appendCustomEntry(customType, data);
|
|
},
|
|
getActiveToolsHandler: () => session.getActiveToolNames(),
|
|
getAllToolsHandler: () => session.getAllToolNames(),
|
|
setActiveToolsHandler: (toolNames: string[]) => session.setActiveToolsByName(toolNames),
|
|
});
|
|
extensionRunner.onError((err) => {
|
|
console.error(`Extension error (${err.extensionPath}): ${err.error}`);
|
|
});
|
|
// Emit session_start event
|
|
await extensionRunner.emit({
|
|
type: "session_start",
|
|
});
|
|
}
|
|
|
|
// Always subscribe to enable session persistence via _handleAgentEvent
|
|
session.subscribe((event) => {
|
|
// In JSON mode, output all events
|
|
if (mode === "json") {
|
|
console.log(JSON.stringify(event));
|
|
}
|
|
});
|
|
|
|
// Send initial message with attachments
|
|
if (initialMessage) {
|
|
await session.prompt(initialMessage, { images: initialImages });
|
|
}
|
|
|
|
// Send remaining messages
|
|
for (const message of messages) {
|
|
await session.prompt(message);
|
|
}
|
|
|
|
// In text mode, output final response
|
|
if (mode === "text") {
|
|
const state = session.state;
|
|
const lastMessage = state.messages[state.messages.length - 1];
|
|
|
|
if (lastMessage?.role === "assistant") {
|
|
const assistantMsg = lastMessage as AssistantMessage;
|
|
|
|
// Check for error/aborted
|
|
if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {
|
|
console.error(assistantMsg.errorMessage || `Request ${assistantMsg.stopReason}`);
|
|
process.exit(1);
|
|
}
|
|
|
|
// Output text content
|
|
for (const content of assistantMsg.content) {
|
|
if (content.type === "text") {
|
|
console.log(content.text);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Ensure stdout is fully flushed before returning
|
|
// This prevents race conditions where the process exits before all output is written
|
|
await new Promise<void>((resolve, reject) => {
|
|
process.stdout.write("", (err) => {
|
|
if (err) reject(err);
|
|
else resolve();
|
|
});
|
|
});
|
|
}
|