09-api-keys-and-oauth.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * API Keys and OAuth
  3. *
  4. * Configure API key resolution via AuthStorage and ModelRegistry.
  5. */
  6. import { AuthStorage, createAgentSession, ModelRegistry, SessionManager } from "@earendil-works/pi-coding-agent";
  7. // Default: AuthStorage uses ~/.pi/agent/auth.json
  8. // ModelRegistry loads built-in + custom models from ~/.pi/agent/models.json
  9. const authStorage = AuthStorage.create();
  10. const modelRegistry = ModelRegistry.create(authStorage);
  11. const { session: defaultAuthSession } = await createAgentSession({
  12. sessionManager: SessionManager.inMemory(),
  13. authStorage,
  14. modelRegistry,
  15. });
  16. console.log("Session with default auth storage and model registry");
  17. defaultAuthSession.dispose();
  18. // Custom auth storage location
  19. const customAuthStorage = AuthStorage.create("/tmp/my-app/auth.json");
  20. const customModelRegistry = ModelRegistry.create(customAuthStorage, "/tmp/my-app/models.json");
  21. const { session: customAuthSession } = await createAgentSession({
  22. sessionManager: SessionManager.inMemory(),
  23. authStorage: customAuthStorage,
  24. modelRegistry: customModelRegistry,
  25. });
  26. console.log("Session with custom auth storage location");
  27. customAuthSession.dispose();
  28. // Runtime API key override (not persisted to disk)
  29. authStorage.setRuntimeApiKey("anthropic", "sk-my-temp-key");
  30. const { session: runtimeKeySession } = await createAgentSession({
  31. sessionManager: SessionManager.inMemory(),
  32. authStorage,
  33. modelRegistry,
  34. });
  35. console.log("Session with runtime API key override");
  36. runtimeKeySession.dispose();
  37. // No models.json - only built-in models
  38. const simpleRegistry = ModelRegistry.inMemory(authStorage);
  39. const { session: builtInModelsSession } = await createAgentSession({
  40. sessionManager: SessionManager.inMemory(),
  41. authStorage,
  42. modelRegistry: simpleRegistry,
  43. });
  44. console.log("Session with only built-in models");
  45. builtInModelsSession.dispose();