From e2cb297b5aa4d75043371f6ed130fe474857cc76 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 10 Feb 2026 14:34:42 +0000 Subject: [PATCH] Extract process and todo runtime services into shared package Co-authored-by: Theo Browne --- apps/desktop/package.json | 1 + apps/desktop/src/processManager.ts | 148 +------------------- apps/desktop/src/todoStore.ts | 107 +------------- apps/t3/package.json | 1 + apps/t3/src/runtimeApiServer.ts | 8 +- bun.lock | 16 +++ packages/runtime-core/package.json | 27 ++++ packages/runtime-core/src/index.ts | 2 + packages/runtime-core/src/processManager.ts | 144 +++++++++++++++++++ packages/runtime-core/src/todoStore.ts | 106 ++++++++++++++ packages/runtime-core/tsconfig.json | 7 + 11 files changed, 313 insertions(+), 254 deletions(-) create mode 100644 packages/runtime-core/package.json create mode 100644 packages/runtime-core/src/index.ts create mode 100644 packages/runtime-core/src/processManager.ts create mode 100644 packages/runtime-core/src/todoStore.ts create mode 100644 packages/runtime-core/tsconfig.json diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c5880b24aa..4696c0cabc 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -8,6 +8,7 @@ }, "dependencies": { "@acme/contracts": "workspace:*", + "@acme/runtime-core": "workspace:*", "node-pty": "^1.0.0" }, "devDependencies": { diff --git a/apps/desktop/src/processManager.ts b/apps/desktop/src/processManager.ts index 7297615a90..bf7122c98b 100644 --- a/apps/desktop/src/processManager.ts +++ b/apps/desktop/src/processManager.ts @@ -1,144 +1,4 @@ -import { type ChildProcess, spawn } from "node:child_process"; -import { randomUUID } from "node:crypto"; -import { EventEmitter } from "node:events"; - -import { - type AgentConfig, - type AgentExit, - type OutputChunk, - agentConfigSchema, -} from "@acme/contracts"; -import type { IPty } from "node-pty"; - -export interface ProcessManagerEvents { - output: [chunk: OutputChunk]; - exit: [exit: AgentExit]; -} - -export class ProcessManager extends EventEmitter { - private sessions = new Map(); - private ptySessions = new Map(); - - spawn(raw: AgentConfig): string { - const config = agentConfigSchema.parse(raw); - const sessionId = randomUUID(); - - if (config.usePty) { - return this.spawnPty(sessionId, config); - } - - return this.spawnProcess(sessionId, config); - } - - private spawnProcess(sessionId: string, config: AgentConfig): string { - const child = spawn(config.command, config.args, { - cwd: config.cwd, - env: config.env ? { ...process.env, ...config.env } : process.env, - stdio: ["pipe", "pipe", "pipe"], - }); - - this.sessions.set(sessionId, child); - - child.stdout?.on("data", (data: Buffer) => { - this.emit("output", { - sessionId, - stream: "stdout", - data: data.toString(), - }); - }); - - child.stderr?.on("data", (data: Buffer) => { - this.emit("output", { - sessionId, - stream: "stderr", - data: data.toString(), - }); - }); - - child.on("exit", (code, signal) => { - this.sessions.delete(sessionId); - this.emit("exit", { - sessionId, - code: code ?? null, - signal: signal ?? null, - }); - }); - - return sessionId; - } - - private spawnPty(sessionId: string, config: AgentConfig): string { - const pty = require("node-pty") as typeof import("node-pty"); - - const ptyProcess = pty.spawn(config.command, config.args, { - name: "xterm-256color", - cols: 120, - rows: 30, - cwd: config.cwd ?? process.cwd(), - env: (config.env ? { ...process.env, ...config.env } : process.env) as Record, - }); - - this.ptySessions.set(sessionId, ptyProcess); - - ptyProcess.onData((data) => { - this.emit("output", { - sessionId, - stream: "stdout", - data, - }); - }); - - ptyProcess.onExit(({ exitCode, signal }) => { - this.ptySessions.delete(sessionId); - this.emit("exit", { - sessionId, - code: exitCode, - signal: signal !== undefined ? String(signal) : null, - }); - }); - - return sessionId; - } - - write(sessionId: string, data: string): void { - const child = this.sessions.get(sessionId); - if (child) { - child.stdin?.write(data); - return; - } - - const pty = this.ptySessions.get(sessionId); - if (pty) { - pty.write(data); - return; - } - - throw new Error(`No session: ${sessionId}`); - } - - kill(sessionId: string): void { - const child = this.sessions.get(sessionId); - if (child) { - child.kill(); - return; - } - - const pty = this.ptySessions.get(sessionId); - if (pty) { - pty.kill(); - return; - } - } - - killAll(): void { - for (const child of this.sessions.values()) { - child.kill(); - } - this.sessions.clear(); - - for (const pty of this.ptySessions.values()) { - pty.kill(); - } - this.ptySessions.clear(); - } -} +export { + ProcessManager, + type ProcessManagerEvents, +} from "@acme/runtime-core"; diff --git a/apps/desktop/src/todoStore.ts b/apps/desktop/src/todoStore.ts index a27ec06020..2a682edb08 100644 --- a/apps/desktop/src/todoStore.ts +++ b/apps/desktop/src/todoStore.ts @@ -1,106 +1 @@ -import { randomUUID } from "node:crypto"; -import { promises as fs } from "node:fs"; -import path from "node:path"; - -import { - type NewTodoInput, - type Todo, - newTodoInputSchema, - todoIdSchema, - todoListSchema, -} from "@acme/contracts"; - -export class TodoStore { - private todos: Todo[] = []; - private queue: Promise = Promise.resolve(); - - public constructor(private readonly filePath: string) {} - - public async init(): Promise { - return this.runExclusive(async () => { - await fs.mkdir(path.dirname(this.filePath), { recursive: true }); - - try { - const raw = await fs.readFile(this.filePath, "utf8"); - const parsed = todoListSchema.safeParse(JSON.parse(raw)); - - if (parsed.success) { - this.todos = parsed.data; - return; - } - } catch (error) { - if (!isNotFoundError(error)) { - throw error; - } - } - - this.todos = []; - await this.persist(); - }); - } - - public async list(): Promise { - return this.runExclusive(async () => [...this.todos]); - } - - public async add(input: NewTodoInput): Promise { - return this.runExclusive(async () => { - const { title } = newTodoInputSchema.parse(input); - const todo: Todo = { - id: randomUUID(), - title, - completed: false, - createdAt: new Date().toISOString(), - }; - - this.todos = [todo, ...this.todos]; - await this.persist(); - return [...this.todos]; - }); - } - - public async toggle(id: string): Promise { - return this.runExclusive(async () => { - const parsedId = todoIdSchema.parse(id); - this.todos = this.todos.map((todo) => - todo.id === parsedId ? { ...todo, completed: !todo.completed } : todo, - ); - - await this.persist(); - return [...this.todos]; - }); - } - - public async remove(id: string): Promise { - return this.runExclusive(async () => { - const parsedId = todoIdSchema.parse(id); - this.todos = this.todos.filter((todo) => todo.id !== parsedId); - - await this.persist(); - return [...this.todos]; - }); - } - - private async persist(): Promise { - await fs.writeFile(this.filePath, JSON.stringify(this.todos, null, 2), "utf8"); - } - - private async runExclusive(operation: () => Promise): Promise { - const next = this.queue.then(operation, operation); - this.queue = next.then( - () => undefined, - () => undefined, - ); - - return next; - } -} - -function isNotFoundError(error: unknown): boolean { - return ( - typeof error === "object" && - error !== null && - "code" in error && - (error as { code?: string }).code === "ENOENT" - ); -} +export { TodoStore } from "@acme/runtime-core"; diff --git a/apps/t3/package.json b/apps/t3/package.json index d21fd6ca61..bdb8feee48 100644 --- a/apps/t3/package.json +++ b/apps/t3/package.json @@ -15,6 +15,7 @@ }, "dependencies": { "@acme/contracts": "workspace:*", + "@acme/runtime-core": "workspace:*", "ws": "^8.18.0", "zod": "^3.24.1" }, diff --git a/apps/t3/src/runtimeApiServer.ts b/apps/t3/src/runtimeApiServer.ts index 044c2a9c62..78f039fccb 100644 --- a/apps/t3/src/runtimeApiServer.ts +++ b/apps/t3/src/runtimeApiServer.ts @@ -41,9 +41,8 @@ import { wsNativeApiMethodSchema, wsServerMessageSchema, } from "@acme/contracts"; -import { ProcessManager } from "../../desktop/src/processManager"; +import { ProcessManager, TodoStore } from "@acme/runtime-core"; import { ProviderManager } from "../../desktop/src/providerManager"; -import { TodoStore } from "../../desktop/src/todoStore"; interface RuntimeApiServerOptions { port: number; @@ -571,7 +570,8 @@ export async function startRuntimeApiServer( throw new Error(`Unknown API method: ${method}`); } - switch (parsedMethod.data) { + const apiMethod = parsedMethod.data; + switch (apiMethod) { case "app.bootstrap": { const bootstrap = await ensureLaunchSession(); const payload = { @@ -673,7 +673,7 @@ export async function startRuntimeApiServer( } default: { - const unreachableMethod: never = parsedMethod.data; + const unreachableMethod: never = apiMethod; throw new Error(`Unknown API method: ${unreachableMethod}`); } } diff --git a/bun.lock b/bun.lock index c0aa50a704..e12c2ec998 100644 --- a/bun.lock +++ b/bun.lock @@ -21,6 +21,7 @@ "version": "0.0.0", "dependencies": { "@acme/contracts": "workspace:*", + "@acme/runtime-core": "workspace:*", "node-pty": "^1.0.0", }, "devDependencies": { @@ -61,6 +62,7 @@ }, "dependencies": { "@acme/contracts": "workspace:*", + "@acme/runtime-core": "workspace:*", "ws": "^8.18.0", "zod": "^3.24.1", }, @@ -83,6 +85,18 @@ "typescript": "^5.7.3", }, }, + "packages/runtime-core": { + "name": "@acme/runtime-core", + "version": "0.0.0", + "dependencies": { + "@acme/contracts": "workspace:*", + "node-pty": "^1.0.0", + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.7.3", + }, + }, }, "packages": { "@acme/contracts": ["@acme/contracts@workspace:packages/contracts"], @@ -91,6 +105,8 @@ "@acme/runtime": ["@acme/runtime@workspace:apps/desktop"], + "@acme/runtime-core": ["@acme/runtime-core@workspace:packages/runtime-core"], + "@acme/t3-runtime": ["@acme/t3-runtime@workspace:apps/t3"], "@babel/code-frame": ["@babel/code-frame@7.29.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="], diff --git a/packages/runtime-core/package.json b/packages/runtime-core/package.json new file mode 100644 index 0000000000..e0d599913f --- /dev/null +++ b/packages/runtime-core/package.json @@ -0,0 +1,27 @@ +{ + "name": "@acme/runtime-core", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "module": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "import": "./src/index.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vitest run --passWithNoTests" + }, + "dependencies": { + "@acme/contracts": "workspace:*", + "node-pty": "^1.0.0" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.7.3" + } +} diff --git a/packages/runtime-core/src/index.ts b/packages/runtime-core/src/index.ts new file mode 100644 index 0000000000..26b309585a --- /dev/null +++ b/packages/runtime-core/src/index.ts @@ -0,0 +1,2 @@ +export * from "./processManager"; +export * from "./todoStore"; diff --git a/packages/runtime-core/src/processManager.ts b/packages/runtime-core/src/processManager.ts new file mode 100644 index 0000000000..7297615a90 --- /dev/null +++ b/packages/runtime-core/src/processManager.ts @@ -0,0 +1,144 @@ +import { type ChildProcess, spawn } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { EventEmitter } from "node:events"; + +import { + type AgentConfig, + type AgentExit, + type OutputChunk, + agentConfigSchema, +} from "@acme/contracts"; +import type { IPty } from "node-pty"; + +export interface ProcessManagerEvents { + output: [chunk: OutputChunk]; + exit: [exit: AgentExit]; +} + +export class ProcessManager extends EventEmitter { + private sessions = new Map(); + private ptySessions = new Map(); + + spawn(raw: AgentConfig): string { + const config = agentConfigSchema.parse(raw); + const sessionId = randomUUID(); + + if (config.usePty) { + return this.spawnPty(sessionId, config); + } + + return this.spawnProcess(sessionId, config); + } + + private spawnProcess(sessionId: string, config: AgentConfig): string { + const child = spawn(config.command, config.args, { + cwd: config.cwd, + env: config.env ? { ...process.env, ...config.env } : process.env, + stdio: ["pipe", "pipe", "pipe"], + }); + + this.sessions.set(sessionId, child); + + child.stdout?.on("data", (data: Buffer) => { + this.emit("output", { + sessionId, + stream: "stdout", + data: data.toString(), + }); + }); + + child.stderr?.on("data", (data: Buffer) => { + this.emit("output", { + sessionId, + stream: "stderr", + data: data.toString(), + }); + }); + + child.on("exit", (code, signal) => { + this.sessions.delete(sessionId); + this.emit("exit", { + sessionId, + code: code ?? null, + signal: signal ?? null, + }); + }); + + return sessionId; + } + + private spawnPty(sessionId: string, config: AgentConfig): string { + const pty = require("node-pty") as typeof import("node-pty"); + + const ptyProcess = pty.spawn(config.command, config.args, { + name: "xterm-256color", + cols: 120, + rows: 30, + cwd: config.cwd ?? process.cwd(), + env: (config.env ? { ...process.env, ...config.env } : process.env) as Record, + }); + + this.ptySessions.set(sessionId, ptyProcess); + + ptyProcess.onData((data) => { + this.emit("output", { + sessionId, + stream: "stdout", + data, + }); + }); + + ptyProcess.onExit(({ exitCode, signal }) => { + this.ptySessions.delete(sessionId); + this.emit("exit", { + sessionId, + code: exitCode, + signal: signal !== undefined ? String(signal) : null, + }); + }); + + return sessionId; + } + + write(sessionId: string, data: string): void { + const child = this.sessions.get(sessionId); + if (child) { + child.stdin?.write(data); + return; + } + + const pty = this.ptySessions.get(sessionId); + if (pty) { + pty.write(data); + return; + } + + throw new Error(`No session: ${sessionId}`); + } + + kill(sessionId: string): void { + const child = this.sessions.get(sessionId); + if (child) { + child.kill(); + return; + } + + const pty = this.ptySessions.get(sessionId); + if (pty) { + pty.kill(); + return; + } + } + + killAll(): void { + for (const child of this.sessions.values()) { + child.kill(); + } + this.sessions.clear(); + + for (const pty of this.ptySessions.values()) { + pty.kill(); + } + this.ptySessions.clear(); + } +} diff --git a/packages/runtime-core/src/todoStore.ts b/packages/runtime-core/src/todoStore.ts new file mode 100644 index 0000000000..a27ec06020 --- /dev/null +++ b/packages/runtime-core/src/todoStore.ts @@ -0,0 +1,106 @@ +import { randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import path from "node:path"; + +import { + type NewTodoInput, + type Todo, + newTodoInputSchema, + todoIdSchema, + todoListSchema, +} from "@acme/contracts"; + +export class TodoStore { + private todos: Todo[] = []; + private queue: Promise = Promise.resolve(); + + public constructor(private readonly filePath: string) {} + + public async init(): Promise { + return this.runExclusive(async () => { + await fs.mkdir(path.dirname(this.filePath), { recursive: true }); + + try { + const raw = await fs.readFile(this.filePath, "utf8"); + const parsed = todoListSchema.safeParse(JSON.parse(raw)); + + if (parsed.success) { + this.todos = parsed.data; + return; + } + } catch (error) { + if (!isNotFoundError(error)) { + throw error; + } + } + + this.todos = []; + await this.persist(); + }); + } + + public async list(): Promise { + return this.runExclusive(async () => [...this.todos]); + } + + public async add(input: NewTodoInput): Promise { + return this.runExclusive(async () => { + const { title } = newTodoInputSchema.parse(input); + const todo: Todo = { + id: randomUUID(), + title, + completed: false, + createdAt: new Date().toISOString(), + }; + + this.todos = [todo, ...this.todos]; + await this.persist(); + return [...this.todos]; + }); + } + + public async toggle(id: string): Promise { + return this.runExclusive(async () => { + const parsedId = todoIdSchema.parse(id); + this.todos = this.todos.map((todo) => + todo.id === parsedId ? { ...todo, completed: !todo.completed } : todo, + ); + + await this.persist(); + return [...this.todos]; + }); + } + + public async remove(id: string): Promise { + return this.runExclusive(async () => { + const parsedId = todoIdSchema.parse(id); + this.todos = this.todos.filter((todo) => todo.id !== parsedId); + + await this.persist(); + return [...this.todos]; + }); + } + + private async persist(): Promise { + await fs.writeFile(this.filePath, JSON.stringify(this.todos, null, 2), "utf8"); + } + + private async runExclusive(operation: () => Promise): Promise { + const next = this.queue.then(operation, operation); + this.queue = next.then( + () => undefined, + () => undefined, + ); + + return next; + } +} + +function isNotFoundError(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error as { code?: string }).code === "ENOENT" + ); +} diff --git a/packages/runtime-core/tsconfig.json b/packages/runtime-core/tsconfig.json new file mode 100644 index 0000000000..374bac5520 --- /dev/null +++ b/packages/runtime-core/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +}