utilities.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /**
  2. * Shared test utilities for coding-agent tests.
  3. */
  4. import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  5. import { homedir, tmpdir } from "node:os";
  6. import { dirname, join } from "node:path";
  7. import { Agent } from "@earendil-works/pi-agent-core";
  8. import { getModel, type OAuthCredentials, type OAuthProvider } from "@earendil-works/pi-ai";
  9. import { getOAuthApiKey } from "@earendil-works/pi-ai/oauth";
  10. import { AgentSession } from "../src/core/agent-session.ts";
  11. import { AuthStorage } from "../src/core/auth-storage.ts";
  12. import { createEventBus } from "../src/core/event-bus.ts";
  13. import type { Extension, ExtensionFactory, LoadExtensionsResult } from "../src/core/extensions/index.ts";
  14. import { createExtensionRuntime, loadExtensionFromFactory } from "../src/core/extensions/loader.ts";
  15. import { ModelRegistry } from "../src/core/model-registry.ts";
  16. import type { ResourceLoader } from "../src/core/resource-loader.ts";
  17. import { SessionManager } from "../src/core/session-manager.ts";
  18. import { SettingsManager } from "../src/core/settings-manager.ts";
  19. import { createCodingTools } from "../src/index.ts";
  20. /**
  21. * API key for authenticated tests. Tests using this should be wrapped in
  22. * describe.skipIf(!API_KEY)
  23. */
  24. export const API_KEY = process.env.ANTHROPIC_OAUTH_TOKEN || process.env.ANTHROPIC_API_KEY;
  25. // ============================================================================
  26. // OAuth API key resolution from ~/.pi/agent/auth.json
  27. // ============================================================================
  28. const AUTH_PATH = join(homedir(), ".pi", "agent", "auth.json");
  29. type ApiKeyCredential = {
  30. type: "api_key";
  31. key: string;
  32. };
  33. type OAuthCredentialEntry = {
  34. type: "oauth";
  35. } & OAuthCredentials;
  36. type AuthCredential = ApiKeyCredential | OAuthCredentialEntry;
  37. type AuthStorageData = Record<string, AuthCredential>;
  38. function loadAuthStorage(): AuthStorageData {
  39. if (!existsSync(AUTH_PATH)) {
  40. return {};
  41. }
  42. try {
  43. const content = readFileSync(AUTH_PATH, "utf-8");
  44. return JSON.parse(content);
  45. } catch {
  46. return {};
  47. }
  48. }
  49. function saveAuthStorage(storage: AuthStorageData): void {
  50. const configDir = dirname(AUTH_PATH);
  51. if (!existsSync(configDir)) {
  52. mkdirSync(configDir, { recursive: true, mode: 0o700 });
  53. }
  54. writeFileSync(AUTH_PATH, JSON.stringify(storage, null, 2), "utf-8");
  55. chmodSync(AUTH_PATH, 0o600);
  56. }
  57. /**
  58. * Resolve API key for a provider from ~/.pi/agent/auth.json
  59. *
  60. * For API key credentials, returns the key directly.
  61. * For OAuth credentials, returns the access token (refreshing if expired and saving back).
  62. *
  63. */
  64. export async function resolveApiKey(provider: string): Promise<string | undefined> {
  65. const storage = loadAuthStorage();
  66. const entry = storage[provider];
  67. if (!entry) return undefined;
  68. if (entry.type === "api_key") {
  69. return entry.key;
  70. }
  71. if (entry.type === "oauth") {
  72. // Build OAuthCredentials record for getOAuthApiKey
  73. const oauthCredentials: Record<string, OAuthCredentials> = {};
  74. for (const [key, value] of Object.entries(storage)) {
  75. if (value.type === "oauth") {
  76. const { type: _, ...creds } = value;
  77. oauthCredentials[key] = creds;
  78. }
  79. }
  80. const result = await getOAuthApiKey(provider as OAuthProvider, oauthCredentials);
  81. if (!result) return undefined;
  82. // Save refreshed credentials back to auth.json
  83. storage[provider] = { type: "oauth", ...result.newCredentials };
  84. saveAuthStorage(storage);
  85. return result.apiKey;
  86. }
  87. return undefined;
  88. }
  89. /**
  90. * Check if a provider has credentials in ~/.pi/agent/auth.json
  91. */
  92. export function hasAuthForProvider(provider: string): boolean {
  93. const storage = loadAuthStorage();
  94. return provider in storage;
  95. }
  96. /** Path to the real pi agent config directory */
  97. export const PI_AGENT_DIR = join(homedir(), ".pi", "agent");
  98. /**
  99. * Get an AuthStorage instance backed by ~/.pi/agent/auth.json
  100. * Use this for tests that need real OAuth credentials.
  101. */
  102. export function getRealAuthStorage(): AuthStorage {
  103. return AuthStorage.create(AUTH_PATH);
  104. }
  105. /**
  106. * Create a minimal user message for testing.
  107. */
  108. export function userMsg(text: string) {
  109. return { role: "user" as const, content: text, timestamp: Date.now() };
  110. }
  111. /**
  112. * Create a minimal assistant message for testing.
  113. */
  114. export function assistantMsg(text: string) {
  115. return {
  116. role: "assistant" as const,
  117. content: [{ type: "text" as const, text }],
  118. api: "anthropic-messages" as const,
  119. provider: "anthropic",
  120. model: "test",
  121. usage: {
  122. input: 1,
  123. output: 1,
  124. cacheRead: 0,
  125. cacheWrite: 0,
  126. totalTokens: 2,
  127. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  128. },
  129. stopReason: "stop" as const,
  130. timestamp: Date.now(),
  131. };
  132. }
  133. /**
  134. * Options for creating a test session.
  135. */
  136. export interface TestSessionOptions {
  137. /** Use in-memory session (no file persistence) */
  138. inMemory?: boolean;
  139. /** Custom system prompt */
  140. systemPrompt?: string;
  141. /** Custom settings overrides */
  142. settingsOverrides?: Record<string, unknown>;
  143. }
  144. /**
  145. * Resources returned by createTestSession that need cleanup.
  146. */
  147. export interface TestSessionContext {
  148. session: AgentSession;
  149. sessionManager: SessionManager;
  150. tempDir: string;
  151. cleanup: () => void;
  152. }
  153. export interface CreateTestExtensionsResultInput {
  154. factory: ExtensionFactory;
  155. path?: string;
  156. }
  157. export async function createTestExtensionsResult(
  158. inputs: Array<ExtensionFactory | CreateTestExtensionsResultInput>,
  159. cwd = process.cwd(),
  160. ): Promise<LoadExtensionsResult> {
  161. const runtime = createExtensionRuntime();
  162. const eventBus = createEventBus();
  163. const extensions: Extension[] = [];
  164. for (const [index, input] of inputs.entries()) {
  165. const factory = typeof input === "function" ? input : input.factory;
  166. const extensionPath =
  167. typeof input === "function" ? `<inline:${index + 1}>` : (input.path ?? `<inline:${index + 1}>`);
  168. extensions.push(await loadExtensionFromFactory(factory, cwd, eventBus, runtime, extensionPath));
  169. }
  170. return {
  171. extensions,
  172. errors: [],
  173. runtime,
  174. };
  175. }
  176. export interface CreateTestResourceLoaderOptions {
  177. extensionsResult?: LoadExtensionsResult;
  178. }
  179. export function createTestResourceLoader(options: CreateTestResourceLoaderOptions = {}): ResourceLoader {
  180. const extensionsResult = options.extensionsResult ?? {
  181. extensions: [],
  182. errors: [],
  183. runtime: createExtensionRuntime(),
  184. };
  185. return {
  186. getExtensions: () => extensionsResult,
  187. getSkills: () => ({ skills: [], diagnostics: [] }),
  188. getPrompts: () => ({ prompts: [], diagnostics: [] }),
  189. getThemes: () => ({ themes: [], diagnostics: [] }),
  190. getAgentsFiles: () => ({ agentsFiles: [] }),
  191. getSystemPrompt: () => undefined,
  192. getAppendSystemPrompt: () => [],
  193. extendResources: () => {},
  194. reload: async () => {},
  195. };
  196. }
  197. /**
  198. * Create an AgentSession for testing with proper setup and cleanup.
  199. * Use this for e2e tests that need real LLM calls.
  200. */
  201. export function createTestSession(options: TestSessionOptions = {}): TestSessionContext {
  202. const tempDir = join(tmpdir(), `pi-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  203. mkdirSync(tempDir, { recursive: true });
  204. const model = getModel("anthropic", "claude-sonnet-4-5")!;
  205. const agent = new Agent({
  206. getApiKey: () => API_KEY,
  207. initialState: {
  208. model,
  209. systemPrompt: options.systemPrompt ?? "You are a helpful assistant. Be extremely concise.",
  210. tools: createCodingTools(process.cwd()),
  211. },
  212. });
  213. const sessionManager = options.inMemory ? SessionManager.inMemory() : SessionManager.create(tempDir);
  214. const settingsManager = SettingsManager.create(tempDir, tempDir);
  215. if (options.settingsOverrides) {
  216. settingsManager.applyOverrides(options.settingsOverrides);
  217. }
  218. const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
  219. const modelRegistry = ModelRegistry.create(authStorage, tempDir);
  220. const session = new AgentSession({
  221. agent,
  222. sessionManager,
  223. settingsManager,
  224. cwd: tempDir,
  225. modelRegistry,
  226. resourceLoader: createTestResourceLoader(),
  227. });
  228. // Must subscribe to enable session persistence
  229. session.subscribe(() => {});
  230. const cleanup = () => {
  231. session.dispose();
  232. if (tempDir && existsSync(tempDir)) {
  233. rmSync(tempDir, { recursive: true });
  234. }
  235. };
  236. return { session, sessionManager, tempDir, cleanup };
  237. }
  238. /**
  239. * Build a session tree for testing using SessionManager.
  240. * Returns the IDs of all created entries.
  241. *
  242. * Example tree structure:
  243. * ```
  244. * u1 -> a1 -> u2 -> a2
  245. * -> u3 -> a3 (branch from a1)
  246. * u4 -> a4 (another root)
  247. * ```
  248. */
  249. export function buildTestTree(
  250. session: SessionManager,
  251. structure: {
  252. messages: Array<{ role: "user" | "assistant"; text: string; branchFrom?: string }>;
  253. },
  254. ): Map<string, string> {
  255. const ids = new Map<string, string>();
  256. for (const msg of structure.messages) {
  257. if (msg.branchFrom) {
  258. const branchFromId = ids.get(msg.branchFrom);
  259. if (!branchFromId) {
  260. throw new Error(`Cannot branch from unknown entry: ${msg.branchFrom}`);
  261. }
  262. session.branch(branchFromId);
  263. }
  264. const id =
  265. msg.role === "user" ? session.appendMessage(userMsg(msg.text)) : session.appendMessage(assistantMsg(msg.text));
  266. ids.set(msg.text, id);
  267. }
  268. return ids;
  269. }