diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 349a21a405222..2b20316c70b49 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -28,6 +28,7 @@ import { serviceLauncherCommand } from "./cli/serviceLauncher.ts"; import { claudeHistoryCommand } from "./cli/claudeHistory.ts"; import { sshHelperCommand } from "./cli/sshHelper.ts"; import { serviceCommand } from "./cli/service.ts"; +import { runnerCommand } from "./cli/runner.ts"; import { servicePreflightCommand } from "./cli/servicePreflight.ts"; import { themeCommand } from "./cli/theme.ts"; import { traceCommand } from "./cli/trace.ts"; @@ -93,6 +94,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => updateCommand, uninstallCommand, serviceLauncherCommand, + runnerCommand, claudeHistoryCommand, sshHelperCommand, diff --git a/apps/server/src/cli/runner.ts b/apps/server/src/cli/runner.ts new file mode 100644 index 0000000000000..feb3d3c4df291 --- /dev/null +++ b/apps/server/src/cli/runner.ts @@ -0,0 +1,41 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the runner serves its own home directory. +import * as NodeOs from "node:os"; + +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { Command, Flag } from "effect/cli"; + +import * as NodePtyAdapter from "../terminal/NodePtyAdapter.ts"; +import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; +import { serveRunner } from "../runner/RunnerServer.ts"; + +export const runnerCommand = Command.make("runner", { + socket: Flag.String("socket").pipe( + Flag.withDescription("Unix socket to listen on. Omit under a systemd socket unit."), + Flag.optional, + ), + allowRoot: Flag.String("allow-root").pipe( + Flag.withDescription("Directory outside the home that work may run in. Repeatable."), + Flag.between(0, 64), + ), +}).pipe( + Command.withDescription( + "Run spawn requests from the T3 server as this user. Started by t3-runner@.service.", + ), + Command.withHandler(({ socket, allowRoot }) => + Effect.gen(function* () { + const pty = yield* PtyAdapter.PtyAdapter; + const runPromise = Effect.runPromiseWith(yield* Effect.context()); + yield* Effect.promise(() => + serveRunner({ + ...(Option.isSome(socket) ? { socketPath: socket.value } : {}), + home: NodeOs.homedir(), + allowedRoots: allowRoot, + env: process.env, + spawnPty: (input) => runPromise(pty.spawn(input)), + }), + ); + return yield* Effect.never; + }).pipe(Effect.provide(NodePtyAdapter.layer)), + ), +); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index bc90fcb2189b4..f55828c9ea7b2 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -138,6 +138,8 @@ import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { PrincipalExecution } from "../../runner/PrincipalExecution.ts"; +import { spawnClaudeViaRunner } from "../../runner/RunnerClient.ts"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts"; @@ -955,6 +957,7 @@ export const layerQueryRunner: Layer.Layer< const runFork = Effect.runForkWith(yield* Effect.context()); const hostEnvironment = yield* HostProcess.Environment; const portDiscovery = yield* PortScanner.PortDiscovery; + const execution = yield* PrincipalExecution; return ClaudeAgentSdkQueryRunner.of({ allocateSessionId: crypto @@ -988,8 +991,12 @@ export const layerQueryRunner: Layer.Layer< }, }; // The SDK can prepend a scope wrapper to native binaries; script entries run through node. + const runner = yield* execution + .runnerFor(input.threadId) + .pipe(Effect.mapError((cause) => queryRunnerError(cause, "runner"))); const binaryPath = queryOptions.pathToClaudeCodeExecutable; const launch = + runner !== undefined || binaryPath === undefined || CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext)) ? undefined @@ -1014,6 +1021,9 @@ export const layerQueryRunner: Layer.Layer< const spawnProcess = options.spawnClaudeCodeProcess ?? ((spawnOptions: ClaudeSpawnOptions) => { + if (runner !== undefined) { + return spawnClaudeViaRunner(runner, spawnOptions, options.stderr) as ClaudeSpawnedProcess; + } if (platform !== "win32") return spawnClaudeProcessGroup(spawnOptions, stopScope); const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, { cwd: spawnOptions.cwd, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index f81a3809b35fe..44efe2bcef283 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -99,6 +99,7 @@ import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { PrincipalExecution, passthroughAgentScope } from "../../runner/PrincipalExecution.ts"; import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachmentStore.ts"; import * as PortScanner from "../../preview/PortScanner.ts"; @@ -1523,10 +1524,21 @@ export const layerAppServerClientFactory: Layer.Layer< const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers; const agentScope = yield* AgentScope; + const execution = yield* PrincipalExecution; return CodexAppServerClientFactory.of({ open: Effect.fn("CodexAdapterV2.open")(function* (input) { const scope = yield* Scope.Scope; + const runnerSpawner = yield* execution.spawnerFor(input.threadId).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterOpenSessionError({ + driver: CODEX_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); const environment = { ...codexAppServerEnvironment(input.environment), ...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}), @@ -1538,8 +1550,10 @@ export const layerAppServerClientFactory: Layer.Layer< ), env: environment, threadId: input.threadId, - }).pipe(Effect.provideService(AgentScope, agentScope)); - const handle = yield* spawner.spawn(command).pipe( + }).pipe( + Effect.provideService(AgentScope, runnerSpawner ? passthroughAgentScope : agentScope), + ); + const handle = yield* (runnerSpawner ?? spawner).spawn(command).pipe( Effect.provideService(Scope.Scope, scope), Effect.mapError( (cause) => diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index dc19cf4cc58c3..5f7c1239aba91 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -520,6 +520,10 @@ export interface ProjectionStoreV2Shape { readonly getThreadsWithPullRequests: ( threadId?: ThreadId, ) => Effect.Effect, ProjectionStoreV2Error>; + /** Non-default principals owning a thread whose worktree is `cwd` or contains it. */ + readonly getWorktreeOwners: ( + cwd: string, + ) => Effect.Effect, ProjectionStoreV2Error>; readonly getThreadWorktreePaths: (options?: { readonly includeArchived?: boolean; }) => Effect.Effect< @@ -6478,6 +6482,24 @@ export const layer: Layer.Layer = Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })), ); + // ponytail: scans threads with a non-default owner per call; index owner and worktree if it shows up in profiles. + const getWorktreeOwners: ProjectionStoreV2Shape["getWorktreeOwners"] = (cwd) => + sql<{ readonly owner: string }>` + SELECT DISTINCT json_extract(payload_json, '$.ownerPrincipal') AS owner + FROM orchestration_v2_projection_threads + WHERE deleted_at IS NULL + AND json_extract(payload_json, '$.ownerPrincipal') IS NOT NULL + AND json_extract(payload_json, '$.ownerPrincipal') != ${DEFAULT_PRINCIPAL_ID} + AND json_extract(payload_json, '$.worktreePath') IS NOT NULL + AND ( + ${cwd} = json_extract(payload_json, '$.worktreePath') + OR substr(${cwd}, 1, length(json_extract(payload_json, '$.worktreePath')) + 1) = json_extract(payload_json, '$.worktreePath') || '/' + ) + `.pipe( + Effect.map((rows) => rows.map((row) => row.owner)), + Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })), + ); + const getThreadWorktreePaths: ProjectionStoreV2Shape["getThreadWorktreePaths"] = (options) => sql<{ readonly thread_id: string; readonly worktree_path: string }>` SELECT thread_id, json_extract(payload_json, '$.worktreePath') AS worktree_path @@ -7094,6 +7116,7 @@ export const layer: Layer.Layer = getThread: readOnReader(getThread), getSettlementCandidates: readOnReader(getSettlementCandidates), getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests), + getWorktreeOwners: readOnReader(getWorktreeOwners), getThreadWorktreePaths: readOnReader(getThreadWorktreePaths), getOpenRemoteDelegatedTasks: getOpenRemoteDelegatedTasks.pipe(NodeSqliteClient.readOnly), getThreadProjection, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 03a7278774a64..fd2894b8fe78c 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -1,4 +1,5 @@ import { AgentScope } from "@t3tools/shared/AgentScope"; +import { PrincipalExecution, requireRunnerSupport } from "../runner/PrincipalExecution.ts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { @@ -346,6 +347,7 @@ export const layerWithOptions = ( const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2; const projectionStore = yield* ProjectionStore.ProjectionStoreV2; const agentScope = yield* AgentScope; + const principalExecution = yield* PrincipalExecution; const agentAccessSettings = Effect.fn("ProviderSessionManagerV2.agentAccessSettings")( function* (threadId: ThreadId) { if (Option.isNone(serverSettings)) return { browser: true, device: false }; @@ -2165,6 +2167,16 @@ export const layerWithOptions = ( }), ), ); + yield* requireRunnerSupport(principalExecution, input.threadId, adapter.driver).pipe( + Effect.mapError( + (cause) => + new ProviderSessionOpenError({ + instanceId: input.modelSelection.instanceId, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); const prepared = yield* prepareMcpSession( input.threadId, input.modelSelection.instanceId, diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 7932a03809c94..27c1ee6b6a19b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -223,6 +223,7 @@ it.effect( getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)), getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"), getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"), + getWorktreeOwners: () => Effect.die("unused getWorktreeOwners"), getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"), getThreadProjection: () => Effect.die("control effects must not load transcript"), getTurnStartContext: () => Effect.die("unused"), diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index a345c67eca881..5f749d2c702bf 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -1,4 +1,5 @@ import * as Context from "effect/Context"; +import { PrincipalExecution } from "./runner/PrincipalExecution.ts"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -390,8 +391,32 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* ( export const make = Effect.fn("ProcessRunner.make")(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const execution = yield* PrincipalExecution; + const run: ProcessRunner["Service"]["run"] = (input) => - finalizeRunProcess(runProcessCore(spawner, input), input); + finalizeRunProcess( + Effect.gen(function* () { + const cwd = input.spawnCwd ?? input.cwd; + const runnerSpawner = cwd === undefined ? undefined : yield* execution.spawnerForPath(cwd); + return yield* runProcessCore(runnerSpawner ?? spawner, input); + }).pipe( + Effect.catchTag("RunnerUnavailableError", (cause) => + Effect.fail( + new ProcessSpawnError({ + command: input.command, + argumentCount: input.args.length, + cwd: input.cwd, + spawnCwd: input.spawnCwd, + resolvedCommand: input.command, + resolvedArgumentCount: input.args.length, + shell: false, + cause, + }), + ), + ), + ), + input, + ); return ProcessRunner.of({ run, diff --git a/apps/server/src/runner/PrincipalExecution.ts b/apps/server/src/runner/PrincipalExecution.ts new file mode 100644 index 0000000000000..68e7644ab8b86 --- /dev/null +++ b/apps/server/src/runner/PrincipalExecution.ts @@ -0,0 +1,182 @@ +import { DEFAULT_PRINCIPAL_ID } from "@t3tools/contracts"; +import type { AgentScopeShape } from "@t3tools/shared/AgentScope"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; +import * as Config from "effect/Config"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { makeRunnerPtyAdapter, makeRunnerSpawner, type RunnerEndpoint } from "./RunnerClient.ts"; + +export class RunnerUnavailableError extends Schema.TaggedError()( + "RunnerUnavailableError", + { principal: Schema.String, socketPath: Schema.String, reason: Schema.String }, +) { + override get message(): string { + return `The runner for principal '${this.principal}' is unavailable at ${this.socketPath}: ${this.reason}. Work is not run as the server user.`; + } +} + +/** Where a thread's work runs. `undefined` means in this process, as the server user. */ +export interface PrincipalExecutionShape { + readonly spawnerFor: ( + threadId: string, + ) => Effect.Effect; + readonly ptyFor: ( + threadId: string, + ) => Effect.Effect; + readonly runnerFor: (threadId: string) => Effect.Effect; + /** Work inside a non-default principal's thread worktree belongs to that principal's runner. */ + readonly spawnerForPath: ( + cwd: string, + ) => Effect.Effect; +} + +const unwired: PrincipalExecutionShape = { + spawnerFor: () => Effect.undefined, + ptyFor: () => Effect.undefined, + runnerFor: () => Effect.undefined, + spawnerForPath: () => Effect.undefined, +}; + +// ponytail: one server per process, so the live layer installs itself here; layers memoized +// outside its scope still reach it. Unwired code and single-user installs spawn in-process. +let installed: PrincipalExecutionShape | undefined; +const current = () => installed ?? unwired; + +export const PrincipalExecution = Context.Reference( + "t3/runner/PrincipalExecution", + { + defaultValue: () => ({ + spawnerFor: (threadId) => current().spawnerFor(threadId), + ptyFor: (threadId) => current().ptyFor(threadId), + runnerFor: (threadId) => current().runnerFor(threadId), + spawnerForPath: (cwd) => current().spawnerForPath(cwd), + }), + }, +); + +/** Principal ids are Linux user names, so anything else could not name a runner and must not reach a path. */ +const USERNAME = /^[a-z_][a-z0-9_-]{0,31}$/; + +export const runnerSocketPath = (template: string, principal: string) => + template.replaceAll("%u", principal); + +export const passthroughAgentScope: AgentScopeShape = { + wrap: ({ command, args }) => Effect.succeed({ command, args }), + oomKilled: () => Effect.succeed(false), + stop: () => Effect.void, + kill: () => Effect.succeed(false), + clear: () => Effect.void, +}; + +export const makePrincipalExecution = (input: { + readonly ownerOf: (threadId: string) => Effect.Effect; + readonly ownersOfPath: (cwd: string) => Effect.Effect, ProjectionStore.ProjectionStoreV2Error>; + readonly socketExists: (socketPath: string) => Effect.Effect; + readonly socketTemplate: string; + readonly serverEnv: NodeJS.ProcessEnv; +}): PrincipalExecutionShape => { + const unreadable = (cause: unknown) => + new RunnerUnavailableError({ + principal: "unknown", + socketPath: input.socketTemplate, + reason: `could not read the owner (${String(cause)})`, + }); + const endpointFor = Effect.fn("PrincipalExecution.endpointFor")(function* (principal: string) { + if (principal === DEFAULT_PRINCIPAL_ID) return undefined; + const socketPath = runnerSocketPath(input.socketTemplate, USERNAME.test(principal) ? principal : "invalid"); + if (!USERNAME.test(principal)) { + return yield* new RunnerUnavailableError({ principal, socketPath, reason: "not a valid Linux user name" }); + } + if (!(yield* input.socketExists(socketPath))) { + return yield* new RunnerUnavailableError({ principal, socketPath, reason: "no runner socket" }); + } + return { socketPath, serverEnv: input.serverEnv, principal } satisfies RunnerEndpoint; + }); + const runnerFor = Effect.fn("PrincipalExecution.runnerFor")(function* (threadId: string) { + const owner = yield* input.ownerOf(threadId).pipe(Effect.mapError(unreadable)); + return yield* endpointFor(owner ?? DEFAULT_PRINCIPAL_ID); + }); + const runnerForPath = Effect.fn("PrincipalExecution.runnerForPath")(function* (cwd: string) { + const owners = yield* input.ownersOfPath(cwd).pipe(Effect.mapError(unreadable)); + if (owners.length === 0) return undefined; + if (owners.length > 1) { + return yield* new RunnerUnavailableError({ + principal: owners.join(","), + socketPath: cwd, + reason: "several principals own threads in this directory", + }); + } + return yield* endpointFor(owners[0]!); + }); + return { + runnerFor, + spawnerFor: (threadId) => + runnerFor(threadId).pipe(Effect.map((endpoint) => endpoint && makeRunnerSpawner(endpoint))), + ptyFor: (threadId) => + runnerFor(threadId).pipe(Effect.map((endpoint) => endpoint && makeRunnerPtyAdapter(endpoint))), + spawnerForPath: (cwd) => + runnerForPath(cwd).pipe(Effect.map((endpoint) => endpoint && makeRunnerSpawner(endpoint))), + }; +}; + +export const layer = Layer.effect( + PrincipalExecution, + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const fs = yield* FileSystem.FileSystem; + const serverEnv = yield* HostProcess.Environment; + const socketTemplate = yield* Config.String("T3CODE_RUNNER_SOCKET_TEMPLATE").pipe( + Config.withDefault("/run/t3code/runner-%u.sock"), + ); + const shape = makePrincipalExecution({ + ownersOfPath: store.getWorktreeOwners, + ownerOf: (threadId) => + store.getThreadShell(threadId as never).pipe( + Effect.map((shell) => shell?.ownerPrincipal), + ), + socketExists: (socketPath) => + fs.stat(socketPath).pipe( + Effect.map((info) => info.type === "Socket"), + Effect.orElseSucceed(() => false), + ), + socketTemplate, + serverEnv, + }); + yield* Effect.acquireRelease( + Effect.sync(() => void (installed = shape)), + () => Effect.sync(() => void (installed = undefined)), + ); + return shape; + }), +); + +export class ProviderRunnerUnsupportedError extends Schema.TaggedError()( + "ProviderRunnerUnsupportedError", + { driver: Schema.String, principal: Schema.String }, +) { + override get message(): string { + return `Provider '${this.driver}' is not supported for signed-in users yet: it would run as the server user instead of '${this.principal}'.`; + } +} + +/** Drivers whose processes go through the runner; every other driver spawns in-process and so must not serve a runner principal. */ +const RUNNER_DRIVERS: ReadonlySet = new Set(["codex", "claudeAgent", "remote"]); + +export const requireRunnerSupport = Effect.fn("PrincipalExecution.requireRunnerSupport")(function* ( + execution: PrincipalExecutionShape, + threadId: string, + driver: string, +) { + if (RUNNER_DRIVERS.has(driver)) return; + const runner = yield* execution.runnerFor(threadId); + if (runner !== undefined) { + return yield* new ProviderRunnerUnsupportedError({ driver, principal: runner.principal ?? "unknown" }); + } +}); diff --git a/apps/server/src/runner/Runner.test.ts b/apps/server/src/runner/Runner.test.ts new file mode 100644 index 0000000000000..181c8289d7cd2 --- /dev/null +++ b/apps/server/src/runner/Runner.test.ts @@ -0,0 +1,192 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the fixture runner binds a real unix socket. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFs from "node:fs"; +import * as NodeNet from "node:net"; +import * as NodeOs from "node:os"; +import * as NodePath from "node:path"; + +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Stream from "effect/Stream"; +import { ChildProcess } from "effect/process"; + +import { + makePrincipalExecution, + ProviderRunnerUnsupportedError, + requireRunnerSupport, +} from "./PrincipalExecution.ts"; +import { readFrames, sendFrame, type RunnerFrame } from "./protocol.ts"; +import { makeRunnerPtyAdapter, makeRunnerSpawner } from "./RunnerClient.ts"; +import { serveRunner } from "./RunnerServer.ts"; + +const serverEnv = { HOME: "/var/lib/t3code", SERVER_SECRET: "s3cret" }; + +const fakePty: Parameters[0]["spawnPty"] = async (input) => { + const child = NodeChildProcess.spawn(input.shell, input.args ?? [], { cwd: input.cwd, env: input.env }); + child.stdout.setEncoding("utf8"); + return { + pid: child.pid!, + write: (data) => void child.stdin.write(data), + resize: () => {}, + kill: (signal) => void child.kill(signal as NodeJS.Signals), + onData: (callback) => { + child.stdout.on("data", callback); + return () => {}; + }, + onExit: (callback) => { + child.on("exit", (code) => callback({ exitCode: code ?? -1, signal: null })); + return () => {}; + }, + }; +}; + +const withRunner = (use: (input: { socketPath: string; home: string }) => Effect.Effect) => + Effect.acquireUseRelease( + Effect.promise(async () => { + const home = NodeFs.realpathSync(NodeFs.mkdtempSync(NodePath.join(NodeOs.tmpdir(), "t3r-"))); + const socketPath = NodePath.join(home, "dejana.sock"); + const server = await serveRunner({ + socketPath, + home, + allowedRoots: [], + env: { PATH: process.env["PATH"] ?? "", HOME: home }, + spawnPty: fakePty, + }); + return { server, socketPath, home }; + }), + ({ socketPath, home }) => use({ socketPath, home }), + ({ server, home }) => + Effect.sync(() => { + server.close(); + NodeFs.rmSync(home, { recursive: true, force: true }); + }), + ); + +const runShell = (spawner: ReturnType, script: string, options: object) => + Effect.scoped( + spawner.spawn(ChildProcess.make("/bin/sh", ["-c", script], options)).pipe( + Effect.flatMap((handle) => + Stream.mkString(Stream.decodeText(handle.stdout)).pipe( + Effect.zip(handle.exitCode), + ), + ), + ), + ); + +const rawRequest = (socketPath: string, frame: Parameters[1]) => + Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(socketPath, () => sendFrame(socket, frame)); + readFrames(socket, (raw) => { resolve(raw as RunnerFrame); socket.destroy(); }, () => {}); + }), + ); + +describe("runner", () => { + it.live("runs a process in the requested cwd with the overlaid env and the runner's own HOME", () => + withRunner(({ socketPath, home }) => + Effect.gen(function* () { + const spawner = makeRunnerSpawner({ socketPath, serverEnv }); + const [out, code] = yield* runShell(spawner, 'pwd; echo "$FOO|$HOME|$SERVER_SECRET"', { + cwd: home, + env: { ...serverEnv, FOO: "bar", HOME: "/evil" }, + }); + expect(code).toBe(0); + expect(out).toBe(`${home}\nbar|${home}|\n`); + }), + ), + ); + + it.live("rejects a cwd outside the allowed roots and protected env keys", () => + withRunner(({ socketPath }) => + Effect.gen(function* () { + const spawner = makeRunnerSpawner({ socketPath, serverEnv }); + const escaped = yield* Effect.exit(runShell(spawner, "true", { cwd: "/" })); + expect(Exit.isFailure(escaped)).toBe(true); + const base = { t: "spawn", kind: "process", command: "true", args: [], stdin: "ignore" } as const; + expect(yield* rawRequest(socketPath, { ...base, env: { PATH: "/evil" } })).toMatchObject({ + t: "error", + message: "Environment override of PATH is not allowed.", + }); + expect(yield* rawRequest(socketPath, { ...base, env: {}, cwd: "relative" })).toMatchObject({ + t: "error", + }); + }), + ), + ); + + it.live("sends non-default principals to their runner and the default one in-process", () => + withRunner(({ socketPath, home }) => + Effect.gen(function* () { + const execution = makePrincipalExecution({ + ownerOf: (threadId) => Effect.succeed(threadId === "mine" ? undefined : "dejana"), + ownersOfPath: (cwd) => Effect.succeed(cwd.startsWith(home) ? ["dejana"] : []), + socketExists: (path) => Effect.succeed(path === socketPath), + socketTemplate: NodePath.join(home, "%u.sock"), + serverEnv, + }); + expect(yield* execution.spawnerFor("mine")).toBeUndefined(); + const spawner = yield* execution.spawnerFor("theirs"); + const [out] = yield* runShell(spawner!, "echo $HOME", { cwd: home }); + expect(out).toBe(`${home}\n`); + expect(yield* execution.spawnerForPath("/srv/elsewhere")).toBeUndefined(); + expect(yield* execution.spawnerForPath(home)).toBeDefined(); + }), + ), + ); + + it.live("runs a terminal in the runner and streams data, input and exit", () => + withRunner(({ socketPath, home }) => + Effect.gen(function* () { + const pty = makeRunnerPtyAdapter({ socketPath, serverEnv }); + const process = yield* pty.spawn({ shell: "/bin/sh", args: ["-c", "exec cat"], cwd: home, cols: 80, rows: 24, env: {} }); + const echoed = new Promise((resolve) => { + let seen = ""; + process.onData((data) => { + seen += data; + if (seen.includes("hi\n")) resolve(seen); + }); + }); + const exited = new Promise((resolve) => process.onExit((event) => resolve(event.exitCode))); + process.write("hi\n"); + expect(yield* Effect.promise(() => echoed)).toContain("hi"); + process.kill("SIGTERM"); + expect(yield* Effect.promise(() => exited)).toBeDefined(); + }), + ), + ); + + it.live("fails closed when the runner socket is missing or the principal is not a user name", () => + Effect.gen(function* () { + const execution = makePrincipalExecution({ + ownerOf: (threadId) => Effect.succeed(threadId), + ownersOfPath: () => Effect.succeed([]), + socketExists: () => Effect.succeed(false), + socketTemplate: "/run/t3code/runner-%u.sock", + serverEnv, + }); + const missing = yield* Effect.flip(execution.spawnerFor("dejana")); + expect(missing.message).toContain("/run/t3code/runner-dejana.sock"); + const traversal = yield* Effect.flip(execution.runnerFor("../../etc/x")); + expect(traversal.socketPath).not.toContain(".."); + }), + ); + + it.live("fails closed for providers that spawn in-process when a runner principal owns the thread", () => + Effect.gen(function* () { + const execution = makePrincipalExecution({ + ownerOf: (threadId) => Effect.succeed(threadId === "mine" ? undefined : "dejana"), + ownersOfPath: () => Effect.succeed([]), + socketExists: () => Effect.succeed(true), + socketTemplate: "/run/t3code/runner-%u.sock", + serverEnv, + }); + yield* requireRunnerSupport(execution, "mine", "cursor"); + yield* requireRunnerSupport(execution, "theirs", "codex"); + const refused = yield* Effect.flip(requireRunnerSupport(execution, "theirs", "cursor")); + expect(refused).toBeInstanceOf(ProviderRunnerUnsupportedError); + expect(refused.message).toContain("not supported for signed-in users yet"); + }), + ); +}); diff --git a/apps/server/src/runner/RunnerClient.ts b/apps/server/src/runner/RunnerClient.ts new file mode 100644 index 0000000000000..64154f8c6d0f3 --- /dev/null +++ b/apps/server/src/runner/RunnerClient.ts @@ -0,0 +1,384 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the client speaks raw unix sockets. +import * as NodeNet from "node:net"; +import { EventEmitter } from "node:events"; +import { PassThrough, Readable, Writable } from "node:stream"; +import { StringDecoder } from "node:string_decoder"; + +import * as NodeSink from "@effect/platform-node-shared/NodeSink"; +import * as NodeStream from "@effect/platform-node-shared/NodeStream"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as PlatformError from "effect/PlatformError"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; + +import { + overlayEnv, + readFrames, + type RunnerFrame, + sendFrame, + type SpawnProcessFrame, + type SpawnPtyFrame, +} from "./protocol.ts"; + +export interface RunnerExit { + readonly code: number | null; + readonly signal: string | null; +} + +export interface RunnerProcess { + readonly pid: number; + readonly stdin: Writable; + readonly stdout: Readable; + readonly stderr: Readable; + readonly exit: Promise; + readonly kill: (signal: string) => void; + readonly resize: (cols: number, rows: number) => void; + readonly dispose: () => void; +} + +const LOST: RunnerExit = { code: null, signal: "SIGKILL" }; + +/** Connects, sends the spawn request and resolves once the runner reports the pid. */ +const openRunnerConnection = ( + socketPath: string, + request: SpawnProcessFrame | SpawnPtyFrame, +) => + new Promise((resolve, reject) => { + const socket = NodeNet.connect(socketPath); + const stdout = new PassThrough(); + const stderr = new PassThrough(); + let settled = false; + let resolveExit!: (exit: RunnerExit) => void; + const exit = new Promise((r) => (resolveExit = r)); + const finish = (result: RunnerExit) => { + resolveExit(result); + stdout.end(); + stderr.end(); + }; + const stdin = new Writable({ + write: (chunk: Buffer, _encoding, callback) => { + sendFrame(socket, { t: "stdin", d: chunk.toString("base64") }, () => callback()); + }, + final: (callback) => { + sendFrame(socket, { t: "stdin-end" }, () => callback()); + }, + }); + const fail = (error: Error) => { + if (settled) return; + settled = true; + socket.destroy(); + reject(error); + }; + + socket.once("connect", () => sendFrame(socket, request)); + socket.on("error", (error) => { + fail(error); + finish(LOST); + }); + socket.on("close", () => { + fail(new Error("The runner closed the connection before starting the process.")); + finish(LOST); + }); + readFrames( + socket, + (raw) => { + const frame = raw as RunnerFrame; + switch (frame.t) { + case "started": + settled = true; + resolve({ + pid: frame.pid, + stdin, + stdout, + stderr, + exit, + kill: (signal) => void sendFrame(socket, { t: "signal", signal }), + resize: (cols, rows) => void sendFrame(socket, { t: "resize", cols, rows }), + dispose: () => socket.destroy(), + }); + break; + case "error": + fail(new Error(frame.message)); + break; + case "out": + (frame.s === "stdout" ? stdout : stderr).write(Buffer.from(frame.d, "base64")); + break; + case "exit": + finish({ code: frame.code, signal: frame.signal }); + break; + } + }, + (message) => fail(new Error(message)), + ); + }); + +export interface RunnerEndpoint { + readonly socketPath: string; + readonly principal?: string; + readonly serverEnv: Readonly>; +} + +export const openRunnerProcess = ( + endpoint: RunnerEndpoint, + input: { + readonly command: string; + readonly args: ReadonlyArray; + readonly cwd?: string | undefined; + readonly env?: Readonly> | undefined; + readonly stdin?: "pipe" | "ignore"; + readonly shell?: boolean | string | undefined; + }, +) => + openRunnerConnection(endpoint.socketPath, { + t: "spawn", + kind: "process", + command: input.command, + args: input.args, + ...(input.cwd === undefined ? {} : { cwd: input.cwd }), + env: overlayEnv(input.env, endpoint.serverEnv), + stdin: input.stdin ?? "pipe", + ...(input.shell ? { shell: input.shell } : {}), + }); + +const platformError = (method: string, command: string, cause: unknown) => + PlatformError.systemError({ + _tag: "Unknown", + module: "ChildProcess", + method, + pathOrDescriptor: command, + description: cause instanceof Error ? cause.message : String(cause), + cause, + }); + +const unsupported = (command: string, what: string) => + Effect.fail(platformError("spawn", command, new Error(`${what} is not supported by the runner.`))); + +/** A `ChildProcessSpawner` whose processes run in the runner behind `endpoint`. */ +export const makeRunnerSpawner = (endpoint: RunnerEndpoint) => + ChildProcessSpawner.make( + Effect.fn("RunnerSpawner.spawn")(function* (command) { + if (!ChildProcess.isStandardCommand(command)) { + return yield* unsupported("pipeline", "Piped commands"); + } + const { options } = command; + if (options.additionalFds !== undefined && Object.keys(options.additionalFds).length > 0) { + return yield* unsupported(command.command, "Additional file descriptors"); + } + const stdinOption = options.stdin; + const stdinConfig = + typeof stdinOption === "object" && stdinOption !== null && "stream" in stdinOption + ? stdinOption.stream + : stdinOption; + const isStream = typeof stdinConfig === "object" && stdinConfig !== null; + for (const output of [options.stdout, options.stderr]) { + const stream = typeof output === "object" && output !== null && "stream" in output ? output.stream : output; + if (typeof stream === "object" && stream !== null) { + return yield* unsupported(command.command, "Custom output sinks"); + } + } + const proc = yield* Effect.acquireRelease( + Effect.tryPromise({ + try: () => + openRunnerProcess(endpoint, { + command: command.command, + args: command.args, + cwd: options.cwd, + env: options.env, + stdin: stdinConfig === "ignore" || stdinConfig === "inherit" ? "ignore" : "pipe", + shell: options.shell, + }), + catch: (cause) => platformError("spawn", command.command, cause), + }), + (spawned) => Effect.sync(() => spawned.dispose()), + ); + const onError = (cause: unknown) => platformError("stream", command.command, cause); + if (isStream) { + yield* Stream.run( + stdinConfig as Stream.Stream, + NodeSink.fromWritable({ evaluate: () => proc.stdin, onError, endOnDone: true }), + ).pipe(Effect.ignore, Effect.forkScoped); + } + const stdout = NodeStream.fromReadable({ + evaluate: () => proc.stdout, + onError, + }); + const stderr = NodeStream.fromReadable({ + evaluate: () => proc.stderr, + onError, + }); + const exited = Effect.promise(() => proc.exit); + let running = true; + void proc.exit.then(() => (running = false)); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(proc.pid), + exitCode: exited.pipe( + Effect.flatMap((exit) => + exit.code === null + ? Effect.fail( + platformError("exitCode", command.command, new Error(`Process ended by signal ${exit.signal}.`)), + ) + : Effect.succeed(ChildProcessSpawner.ExitCode(exit.code)), + ), + ), + isRunning: Effect.sync(() => running), + kill: Effect.fn("RunnerSpawner.kill")(function* (killOptions) { + proc.kill(killOptions?.killSignal ?? "SIGTERM"); + if (killOptions?.forceKillAfter === undefined) return yield* exited; + const graceful = yield* exited.pipe(Effect.timeoutOption(killOptions.forceKillAfter)); + if (Option.isNone(graceful)) { + proc.kill("SIGKILL"); + yield* exited; + } + }), + stdin: isStream || stdinConfig === "ignore" || stdinConfig === "inherit" + ? Sink.drain + : NodeSink.fromWritable({ evaluate: () => proc.stdin, onError, endOnDone: true }), + stdout, + stderr, + all: Stream.merge(stdout, stderr), + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); + }), + ); + +class RunnerPtyProcess implements PtyAdapter.PtyProcess { + private readonly decoder = new StringDecoder("utf8"); + private readonly dataListeners = new Set<(data: string) => void>(); + private exitEvent: PtyAdapter.PtyExitEvent | undefined; + private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>(); + + private readonly proc: RunnerProcess; + + constructor(proc: RunnerProcess) { + this.proc = proc; + proc.stdout.on("data", (chunk: Buffer) => { + const text = this.decoder.write(chunk); + if (text !== "") for (const listener of this.dataListeners) listener(text); + }); + void proc.exit.then(({ code, signal }) => { + this.exitEvent = { + exitCode: code ?? -1, + signal: signal === null ? null : Number(signal) || 1, + }; + for (const listener of this.exitListeners) listener(this.exitEvent); + this.exitListeners.clear(); + proc.dispose(); + }); + } + + get pid() { + return this.proc.pid; + } + write(data: string) { + this.proc.stdin.write(data); + } + resize(cols: number, rows: number) { + this.proc.resize(cols, rows); + } + kill(signal?: string) { + this.proc.kill(signal ?? "SIGHUP"); + } + onData(callback: (data: string) => void) { + this.dataListeners.add(callback); + return () => void this.dataListeners.delete(callback); + } + onExit(callback: (event: PtyAdapter.PtyExitEvent) => void) { + if (this.exitEvent) { + callback(this.exitEvent); + return () => {}; + } + this.exitListeners.add(callback); + return () => void this.exitListeners.delete(callback); + } +} + +/** A `PtyAdapter` whose terminals are owned by the runner behind `endpoint`. */ +export const makeRunnerPtyAdapter = (endpoint: RunnerEndpoint) => + PtyAdapter.PtyAdapter.of({ + spawn: Effect.fn("RunnerPtyAdapter.spawn")(function* (input) { + const proc = yield* Effect.tryPromise({ + try: () => + openRunnerConnection(endpoint.socketPath, { + t: "spawn", + kind: "pty", + command: input.shell, + args: input.args ?? [], + cwd: input.cwd, + env: overlayEnv(input.env, endpoint.serverEnv), + cols: input.cols, + rows: input.rows, + }), + catch: (cause) => + new PtyAdapter.PtySpawnError({ adapter: "runner", shell: input.shell, cause }), + }); + return new RunnerPtyProcess(proc); + }), + }); + +interface ClaudeSpawnOptionsLike { + readonly command: string; + readonly args: ReadonlyArray; + readonly cwd?: string | undefined; + readonly env: Record; + readonly signal: AbortSignal; +} + +/** The synchronous process handle the Claude SDK's `spawnClaudeCodeProcess` hook expects; the runner connection opens behind it. */ +export const spawnClaudeViaRunner = ( + endpoint: RunnerEndpoint, + options: ClaudeSpawnOptionsLike, + onStderr?: (chunk: string) => void, +) => { + const emitter = new EventEmitter(); + const stdin = new PassThrough(); + const stdout = new PassThrough(); + let proc: RunnerProcess | undefined; + let killRequested: string | undefined; + const handle = Object.assign(emitter, { + stdin, + stdout, + killed: false, + exitCode: null as number | null, + signalCode: null as NodeJS.Signals | null, + kill(signal: NodeJS.Signals) { + handle.killed = true; + if (proc) proc.kill(signal); + else killRequested = signal; + return true; + }, + }); + const onAbort = () => handle.kill("SIGTERM"); + if (options.signal.aborted) onAbort(); + else options.signal.addEventListener("abort", onAbort, { once: true }); + openRunnerProcess(endpoint, { + command: options.command, + args: options.args, + cwd: options.cwd, + env: options.env, + }).then( + (opened) => { + proc = opened; + if (killRequested !== undefined) opened.kill(killRequested); + stdin.pipe(opened.stdin); + opened.stdout.pipe(stdout); + opened.stderr.setEncoding("utf8").on("data", (chunk: string) => onStderr?.(chunk)); + void opened.exit.then(({ code, signal }) => { + handle.exitCode = code; + handle.signalCode = signal as NodeJS.Signals | null; + emitter.emit("exit", code, signal); + opened.dispose(); + }); + }, + (cause) => { + stdout.end(); + emitter.emit("error", cause instanceof Error ? cause : new Error(String(cause))); + }, + ); + return handle; +}; diff --git a/apps/server/src/runner/RunnerServer.ts b/apps/server/src/runner/RunnerServer.ts new file mode 100644 index 0000000000000..3636b5d637918 --- /dev/null +++ b/apps/server/src/runner/RunnerServer.ts @@ -0,0 +1,267 @@ +// @effect-diagnostics nodeBuiltinImport:off globalTimers:off -- the runner owns raw sockets, child processes and their exit flush. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFs from "node:fs"; +import * as NodeNet from "node:net"; +import * as NodeOs from "node:os"; +import * as NodePath from "node:path"; + +import type * as PtyAdapter from "@t3tools/shared/PtyAdapter"; + +import { + type ClientFrame, + isProtectedEnvKey, + readFrames, + type RunnerFrame, + sendFrame, + type SpawnProcessFrame, + type SpawnPtyFrame, +} from "./protocol.ts"; + +export interface RunnerServerOptions { + /** Listen here; absent means inherit the socket-activated descriptor 3. */ + readonly socketPath?: string; + readonly home: string; + /** Directories outside `home` that work may run in. */ + readonly allowedRoots: ReadonlyArray; + readonly env: NodeJS.ProcessEnv; + readonly spawnPty: (input: PtyAdapter.PtySpawnInput) => Promise; +} + +const SIGNALS = new Set(Object.keys(NodeOs.constants.signals)); +// Grandchildren that inherit the pipes keep `close` from firing; report the exit regardless. +const EXIT_FLUSH_GRACE_MS = 2_000; + +const within = (root: string, target: string) => { + const relative = NodePath.relative(root, target); + return relative === "" || (!relative.startsWith("..") && !NodePath.isAbsolute(relative)); +}; + +const realpathOrNull = (value: string) => { + try { + return NodeFs.realpathSync(value); + } catch { + return null; + } +}; + +/** Resolves symlinks before comparing, so a link inside the home cannot lead out of it. */ +export const resolveAllowedCwd = ( + cwd: string | undefined, + home: string, + allowedRoots: ReadonlyArray, +): string => { + const requested = cwd ?? home; + if (!NodePath.isAbsolute(requested)) throw new Error(`Working directory must be absolute: ${requested}`); + const real = realpathOrNull(requested); + if (real === null) throw new Error(`Working directory does not exist: ${requested}`); + const roots = [home, ...allowedRoots].flatMap((root) => realpathOrNull(root) ?? []); + if (!roots.some((root) => within(root, real))) { + throw new Error(`Working directory is outside the allowed roots: ${requested}`); + } + return real; +}; + +export const assertAllowedEnv = (env: Readonly>) => { + for (const [key, value] of Object.entries(env)) { + if (typeof value !== "string") throw new Error(`Environment value for ${key} must be a string.`); + if (isProtectedEnvKey(key)) throw new Error(`Environment override of ${key} is not allowed.`); + } +}; + +const decode = (data: string) => Buffer.from(data, "base64"); +const encode = (data: Uint8Array | string) => Buffer.from(data).toString("base64"); + +const killGroup = (pid: number, signal: NodeJS.Signals) => { + try { + process.kill(-pid, signal); + } catch { + try { + process.kill(pid, signal); + } catch {} + } +}; + +const handleConnection = (socket: NodeNet.Socket, options: RunnerServerOptions) => { + let teardown: () => void = () => {}; + let dispatch: ((frame: ClientFrame) => void) | undefined; + const send = (frame: RunnerFrame) => sendFrame(socket, frame); + const fail = (message: string) => { + send({ t: "error", message }); + socket.end(); + }; + + const startProcess = (request: SpawnProcessFrame) => { + const cwd = resolveAllowedCwd(request.cwd, options.home, options.allowedRoots); + assertAllowedEnv(request.env); + if (typeof request.command !== "string" || request.command === "") { + throw new Error("Command must be a non-empty string."); + } + const child = NodeChildProcess.spawn(request.command, [...request.args], { + cwd, + env: { ...options.env, ...request.env }, + detached: true, + shell: request.shell ?? false, + stdio: [request.stdin === "ignore" ? "ignore" : "pipe", "pipe", "pipe"], + }); + let exited = false; + let exitReported = false; + const reportExit = (code: number | null, signal: string | null) => { + if (exitReported) return; + exitReported = true; + send({ t: "exit", code, signal }); + socket.end(); + }; + child.once("error", (error) => { + if (child.pid === undefined) fail(error.message); + }); + child.once("spawn", () => send({ t: "started", pid: child.pid! })); + child.stdout!.on("data", (chunk: Buffer) => send({ t: "out", s: "stdout", d: encode(chunk) })); + child.stderr!.on("data", (chunk: Buffer) => send({ t: "out", s: "stderr", d: encode(chunk) })); + child.stdin?.on("error", () => {}); + child.once("exit", (code, signal) => { + exited = true; + setTimeout(() => reportExit(code, signal), EXIT_FLUSH_GRACE_MS).unref(); + }); + child.once("close", (code, signal) => reportExit(code, signal)); + dispatch = (frame) => { + switch (frame.t) { + case "stdin": + child.stdin?.write(decode(frame.d)); + break; + case "stdin-end": + child.stdin?.end(); + break; + case "signal": + if (SIGNALS.has(frame.signal) && child.pid !== undefined) { + killGroup(child.pid, frame.signal as NodeJS.Signals); + } + break; + } + }; + teardown = () => { + if (child.pid !== undefined) killGroup(child.pid, "SIGKILL"); + if (!exited) child.kill("SIGKILL"); + }; + }; + + const startPty = (request: SpawnPtyFrame) => { + const cwd = resolveAllowedCwd(request.cwd, options.home, options.allowedRoots); + assertAllowedEnv(request.env); + const cols = Number.isInteger(request.cols) && request.cols > 0 ? request.cols : 80; + const rows = Number.isInteger(request.rows) && request.rows > 0 ? request.rows : 24; + const queued: ClientFrame[] = []; + let pty: PtyAdapter.PtyProcess | undefined; + let closed = false; + dispatch = (frame) => { + if (pty === undefined) queued.push(frame); + else applyPty(pty, frame); + }; + const applyPty = (target: PtyAdapter.PtyProcess, frame: ClientFrame) => { + switch (frame.t) { + case "stdin": + target.write(decode(frame.d).toString("utf8")); + break; + case "resize": + if (Number.isInteger(frame.cols) && Number.isInteger(frame.rows)) { + target.resize(frame.cols, frame.rows); + } + break; + case "signal": + if (SIGNALS.has(frame.signal)) target.kill(frame.signal); + break; + } + }; + teardown = () => { + closed = true; + pty?.kill("SIGHUP"); + }; + options + .spawnPty({ + shell: request.command, + args: [...request.args], + cwd, + cols, + rows, + env: { ...options.env, ...request.env }, + }) + .then( + (spawned) => { + if (closed) return spawned.kill("SIGHUP"); + pty = spawned; + spawned.onData((data) => send({ t: "out", s: "stdout", d: encode(data) })); + spawned.onExit(({ exitCode, signal }) => { + send({ t: "exit", code: exitCode, signal: signal === null ? null : String(signal) }); + socket.end(); + }); + send({ t: "started", pid: spawned.pid }); + for (const frame of queued.splice(0)) applyPty(spawned, frame); + }, + (cause) => fail(cause instanceof Error ? cause.message : String(cause)), + ); + }; + + readFrames( + socket, + (raw) => { + const frame = raw as ClientFrame; + if (dispatch !== undefined) return dispatch(frame); + try { + if (frame?.t !== "spawn") throw new Error("The first frame must be a spawn request."); + if (frame.kind === "process") startProcess(frame); + else if (frame.kind === "pty") startPty(frame); + else throw new Error("Unknown spawn kind."); + } catch (cause) { + fail(cause instanceof Error ? cause.message : String(cause)); + } + }, + fail, + ); + socket.on("error", () => {}); + socket.on("close", () => teardown()); +}; + +const isStale = (socketPath: string) => + new Promise((resolve) => { + const probe = NodeNet.connect(socketPath); + probe.once("connect", () => { + probe.destroy(); + resolve(false); + }); + probe.once("error", () => resolve(true)); + }); + +/** + * Serves spawn requests for the user this process runs as. The socket's filesystem permissions are + * the only authentication: whoever can connect can run commands as this user, so the socket must be + * reachable by the T3 server and nobody else (0660, or a systemd socket unit with `SocketGroup`). + */ +export const serveRunner = async (options: RunnerServerOptions) => { + if (process.getuid?.() === 0) throw new Error("The runner must not run as root."); + const server = NodeNet.createServer((socket) => handleConnection(socket, options)); + if (options.socketPath === undefined) { + if (process.env["LISTEN_FDS"] !== "1") { + throw new Error("Pass --socket, or start the runner from a systemd socket unit."); + } + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen({ fd: 3 }, resolve); + }); + return server; + } + const { socketPath } = options; + if (NodeFs.existsSync(socketPath)) { + if (!(await isStale(socketPath))) throw new Error(`A runner is already listening on ${socketPath}.`); + NodeFs.unlinkSync(socketPath); + } + const previousUmask = process.umask(0o117); + try { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, resolve); + }); + } finally { + process.umask(previousUmask); + } + NodeFs.chmodSync(socketPath, 0o660); + return server; +}; diff --git a/apps/server/src/runner/protocol.ts b/apps/server/src/runner/protocol.ts new file mode 100644 index 0000000000000..d8f039e342686 --- /dev/null +++ b/apps/server/src/runner/protocol.ts @@ -0,0 +1,115 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the runner speaks raw unix sockets. +import type { Socket } from "node:net"; + +/** + * One connection is one process. The client opens with a `spawn` frame; both sides then exchange + * newline-delimited JSON frames until `exit`. Closing the connection kills the process, so a + * client's scope exit is the cleanup path. Bytes travel as base64. + */ +export type SpawnProcessFrame = { + readonly t: "spawn"; + readonly kind: "process"; + readonly command: string; + readonly args: ReadonlyArray; + readonly cwd?: string; + readonly env: Readonly>; + readonly stdin: "pipe" | "ignore"; + readonly shell?: boolean | string; +}; + +export type SpawnPtyFrame = { + readonly t: "spawn"; + readonly kind: "pty"; + readonly command: string; + readonly args: ReadonlyArray; + readonly cwd: string; + readonly env: Readonly>; + readonly cols: number; + readonly rows: number; +}; + +export type ClientFrame = + | SpawnProcessFrame + | SpawnPtyFrame + | { readonly t: "stdin"; readonly d: string } + | { readonly t: "stdin-end" } + | { readonly t: "signal"; readonly signal: string } + | { readonly t: "resize"; readonly cols: number; readonly rows: number }; + +export type RunnerFrame = + | { readonly t: "started"; readonly pid: number } + | { readonly t: "error"; readonly message: string } + | { readonly t: "out"; readonly s: "stdout" | "stderr"; readonly d: string } + | { readonly t: "exit"; readonly code: number | null; readonly signal: string | null }; + +export const MAX_FRAME_BYTES = 16 * 1024 * 1024; + +/** Server-side variables the user's own login environment must keep control of. */ +const PROTECTED_ENV_KEYS = new Set([ + "HOME", + "USER", + "LOGNAME", + "SHELL", + "PATH", + "NODE_OPTIONS", + "BASH_ENV", + "ENV", + "IFS", +]); + +export const isProtectedEnvKey = (key: string) => + PROTECTED_ENV_KEYS.has(key) || key.startsWith("LD_") || key.startsWith("DYLD_"); + +/** + * What the client may overlay on the runner's environment: values the caller changed relative to the + * server's own environment, minus protected keys. The server's inherited environment (service + * credentials, its HOME and PATH) never reaches a user's process. + */ +export const overlayEnv = ( + env: Readonly> | undefined, + serverEnv: Readonly>, +): Record => { + const overlay: Record = {}; + for (const [key, value] of Object.entries(env ?? {})) { + if (value === undefined || isProtectedEnvKey(key) || serverEnv[key] === value) continue; + overlay[key] = value; + } + return overlay; +}; + +export const sendFrame = (socket: Socket, frame: ClientFrame | RunnerFrame, cb?: () => void) => { + if (socket.destroyed || !socket.writable) return false; + return socket.write(`${JSON.stringify(frame)}\n`, cb); +}; + +/** Splits a socket into JSON frames; a malformed or oversized line is reported once and stops reading. */ +export const readFrames = ( + socket: Socket, + onFrame: (frame: unknown) => void, + onProtocolError: (message: string) => void, +) => { + let buffer = ""; + let failed = false; + socket.setEncoding("utf8"); + socket.on("data", (chunk: string) => { + if (failed) return; + buffer += chunk; + let newline = buffer.indexOf("\n"); + while (newline !== -1) { + const line = buffer.slice(0, newline); + buffer = buffer.slice(newline + 1); + try { + onFrame(JSON.parse(line)); + } catch (cause) { + failed = true; + onProtocolError(`Malformed runner frame: ${String(cause)}`); + return; + } + newline = buffer.indexOf("\n"); + } + if (buffer.length > MAX_FRAME_BYTES) { + failed = true; + onProtocolError("Runner frame exceeds the size limit."); + } + }); +}; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 05b9f22a4a419..18353fd121a84 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -37,6 +37,7 @@ import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts"; +import * as PrincipalExecution from "./runner/PrincipalExecution.ts"; import * as PullRequestHttp from "./pullRequest/http.ts"; import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; @@ -486,6 +487,7 @@ const layerCheckpointStore = CheckpointStore.layer.pipe(Layer.provide(layerVcsDr const layerPortScanner = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer)); const layerTerminal = TerminalManager.layer.pipe( + Layer.provide(PrincipalExecution.layer), Layer.provide(layerPtyAdapter), Layer.provide(layerPortScanner), Layer.provide(layerNativeTelemetry), @@ -683,6 +685,8 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( ), Layer.provideMerge(ProviderRegistry.layer), Layer.provideMerge(ProviderInstanceRegistryHydration.layer), + Layer.provideMerge(PrincipalExecution.layer), + Layer.provideMerge(ProjectionStoreV2.layer), // Provider hydration builds the Claude runner, which reports agents to the same scanner the // terminal and preview layers share. Layer.provideMerge(layerPortScanner), diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index c881dbd7b19a8..9cf7e373c072d 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -75,6 +75,7 @@ import * as PortScanner from "../preview/PortScanner.ts"; import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts"; import { terminalOutputStream } from "./OutputProtocol.ts"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; +import { PrincipalExecution } from "../runner/PrincipalExecution.ts"; export { TerminalCwdError, @@ -1552,6 +1553,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const agentScope = yield* AgentScope; + const principalExecution = yield* PrincipalExecution; // Inherit the full environment minus createTerminalSpawnEnv's blocklist; allowlists silently drop user tooling variables. const baseEnv = options.env ?? process.env; const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv)); @@ -2397,15 +2399,21 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); } - const launch = yield* agentScope.wrap({ - command: candidate.shell, - args: candidate.args ?? [], - name: "terminal", - env: spawnEnv, - survivesRestart: true, - }); + const runnerPty = yield* principalExecution.ptyFor(session.threadId).pipe( + Effect.mapError((cause) => new PtyAdapter.PtySpawnError({ adapter: "runner", cause })), + ); + const launch = + runnerPty === undefined + ? yield* agentScope.wrap({ + command: candidate.shell, + args: candidate.args ?? [], + name: "terminal", + env: spawnEnv, + survivesRestart: true, + }) + : { command: candidate.shell, args: [] }; const attempt = yield* Effect.result( - options.ptyAdapter.spawn({ + (runnerPty ?? options.ptyAdapter).spawn({ shell: launch.command, ...(launch.args.length > 0 ? { args: [...launch.args] } : {}), cwd: session.cwd, diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index a084664bc447c..b4354381509c5 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1,4 +1,5 @@ import * as Cache from "effect/Cache"; +import { PrincipalExecution } from "../runner/PrincipalExecution.ts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Data from "effect/Data"; @@ -941,6 +942,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const principalExecution = yield* PrincipalExecution; const { worktreesDir } = yield* ServerConfig.ServerConfig; const isServerInternalPath = yield* makeIsServerInternalPath; const crypto = yield* Crypto.Crypto; @@ -984,7 +986,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolved = yield* resolveSpawnCommand("git", [], { env: spawnEnv }); // cmd wrappers truncate multiline commits; leave git.cmd handling to Node lookup. const executable = resolved.shell ? "git" : resolved.command; - const child = yield* commandSpawner + const runnerSpawner = yield* principalExecution.spawnerForPath(commandInput.cwd).pipe( + Effect.mapError( + (cause) => + new GitCommandError({ + ...gitCommandContext(commandInput), + detail: cause.message, + cause, + }), + ), + ); + const child = yield* (runnerSpawner ?? commandSpawner) .spawn( ChildProcess.make(executable, commandInput.args, { cwd: commandInput.cwd,