13-session-runtime.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Session runtime
  3. *
  4. * Use AgentSessionRuntime when you need to replace the active AgentSession,
  5. * for example for new-session, resume, fork, or import flows.
  6. *
  7. * The important pattern is: after the runtime replaces the active session,
  8. * rebind any session-local subscriptions and extension bindings to `runtime.session`.
  9. */
  10. import {
  11. type CreateAgentSessionRuntimeFactory,
  12. createAgentSessionFromServices,
  13. createAgentSessionRuntime,
  14. createAgentSessionServices,
  15. getAgentDir,
  16. SessionManager,
  17. } from "@earendil-works/pi-coding-agent";
  18. const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => {
  19. const services = await createAgentSessionServices({ cwd });
  20. return {
  21. ...(await createAgentSessionFromServices({
  22. services,
  23. sessionManager,
  24. sessionStartEvent,
  25. })),
  26. services,
  27. diagnostics: services.diagnostics,
  28. };
  29. };
  30. const runtime = await createAgentSessionRuntime(createRuntime, {
  31. cwd: process.cwd(),
  32. agentDir: getAgentDir(),
  33. sessionManager: SessionManager.create(process.cwd()),
  34. });
  35. let unsubscribe: (() => void) | undefined;
  36. async function bindSession() {
  37. unsubscribe?.();
  38. const session = runtime.session;
  39. await session.bindExtensions({});
  40. unsubscribe = session.subscribe((event) => {
  41. if (event.type === "queue_update") {
  42. console.log("Queued:", event.steering.length + event.followUp.length);
  43. }
  44. });
  45. return session;
  46. }
  47. let session = await bindSession();
  48. const originalSessionFile = session.sessionFile;
  49. console.log("Initial session:", originalSessionFile);
  50. await runtime.newSession();
  51. session = await bindSession();
  52. console.log("After newSession():", session.sessionFile);
  53. if (originalSessionFile) {
  54. await runtime.switchSession(originalSessionFile);
  55. session = await bindSession();
  56. console.log("After switchSession():", session.sessionFile);
  57. }
  58. unsubscribe?.();
  59. await runtime.dispose();