An open-source, faster Devin alternative
TypeScript
computer: run root seam (work 103, S1) (#1033)
opencomputer-app[bot]5859227c28bd
diff --git a/computer/src/host/api-host.ts b/computer/src/host/api-host.tsindex 06a43f38..2740f135 100644--- a/computer/src/host/api-host.ts+++ b/computer/src/host/api-host.ts@@ -32,6 +32,7 @@ import type {ApiSessionStatus, Delivery, GatewayToHost, HostCredentials, HostToGateway, JournalReport, ModelRoute, Person,RunnerApi, SessionAccess, SessionSecret, SessionSpec, SessionStatus,} from '../protocol.js';+import { HOST_RUN } from '../protocol.js';import { apiError, RECORD_METHOD } from '../api/writer.js';import { createdOf } from '../api/created.js';import { ensureJournalDir, ensureSessionJournalDir, forgetJournalFile, Journal, journalPath, readJournalFile } from '../api/journal.js';@@ -39,7 +40,7 @@ import { moveFlatJournals, moveFlatSessionLogged } from './journal-flat-move.js'import { journalReports } from './journal-reports.js';import { type HostWriterOptions, HostSessionWriter, scanJournals } from './session-writer.js';import { isSessionId } from '../session-ids.js';-import { RUNNERS_DIR } from '../ipc.js';+import { runnersDir as runnersDirOf } from '../ipc.js';import { log } from '../log.js';import { apiBridge, localPort, type WriterPort } from './api-bridge.js';import { mirrorAcks } from './mirror-acks.js';@@ -108,7 +109,7 @@ export const apiStatus = (s: SessionStatus | undefined): ApiSessionStatus =>const ownerOf = (p: Person | undefined) => ({ id: p?.userId ?? p?.slackUserId ?? '', name: p?.name ?? p?.gitName ?? '', email: p?.email ?? null });export function apiHost(d: ApiHostDeps) {- const runnersDir = d.runnersDir ?? RUNNERS_DIR;+ const runnersDir = d.runnersDir ?? runnersDirOf(HOST_RUN);const journals = path.join(d.dataDir, 'journals');moveFlatJournals(d.dataDir); // before anything below lists or reads a journal (work 103 C8; goes in its step 12)const tokens = runnerApis(path.join(d.runDir, 'runners.json'));diff --git a/computer/src/host/main.ts b/computer/src/host/main.tsindex ec83325e..7bffaeec 100644--- a/computer/src/host/main.ts+++ b/computer/src/host/main.ts@@ -36,7 +36,7 @@ import type net from 'node:net';import os from 'node:os';import path from 'node:path';import { mkdirSync } from 'node:fs';-import { HOST_DATA, HOST_RUN, HOST_TOKEN_SOCKET, PROTOCOL_VERSION, RUNNER_TOKEN_DIR } from '../protocol.js';+import { HOST_DATA, HOST_RUN, HOST_TOKEN_SOCKET, PROTOCOL_VERSION } from '../protocol.js';import { codexBin } from '../runner-env.js';import { prereadCodex } from './codex-preread.js';import type {@@ -68,7 +68,7 @@ import { log } from '../log.js';import { closed, rediscover, retire } from './runner-sockets.js';import { type Runner, runnerStarts } from './start-runner.js';import { Pool } from './pool.js';-import { tokenRelay } from './tokens.js';+import { freshTokenDir, tokenRelay } from './tokens.js';import { hostPreviews } from './previews.js';import { startHostTelemetry, workspaceTelemetry } from './telemetry.js';import { diskReport, hostSampler } from './sample.js';@@ -141,7 +141,7 @@ function switchRunner(key: string, r = runners.get(key)) {}/** Its session's epoch moved on (api-host `epoch`): end its turn now, then exit; killed after 10 s. */const retireRunner = async (id: string, r = [...runners.values()].find((x) => x.id === id)) =>- r && ((r.exiting = true), retire(r.sock, socketFor(r.id), () => void call(r, { t: 'stop' }, 10_000).catch(() => {})));+ r && ((r.exiting = true), retire(r.sock, socketFor(HOST_RUN, r.id), () => void call(r, { t: 'stop' }, 10_000).catch(() => {})));/** spawn, secret and thread requests in flight to the gateway, by id: the runner that asked. */const spawning = new Map<string, Runner>();const starting = new Map<string, Promise<Runner>>();@@ -150,9 +150,9 @@ let stopping = false;/** Starting and adopting runners (start-runner.ts); what it asks for is looked up when used, so `api` and `tokens` below are there by then. */const starts = runnerStarts({- tm, launch: { tm, mode: LAUNCH, env, root: ROOT }, version: VERSION, pool,+ tm, launch: { tm, mode: LAUNCH, env, root: ROOT }, run: HOST_RUN, version: VERSION, pool,creds: () => org.creds, models: subs,- mint: (spec, id) => api.mint(spec, id), serveTokens: (id, sock, session) => tokens.serveRunner(id, sock, session),+ mint: (spec, id) => api.mint(spec, id), serveTokens: (id, session) => tokens.serveRunner(HOST_RUN, id, session),fillPool: () => fillPool(), inFork: (f, fn) => forkContext.run(f, fn),register, closed: runnerClosed, message: onRunner, exit: exitRunner, toGateway,});@@ -427,7 +427,8 @@ function housekeeping() {// ---------------------------------------------------------------- GitHub tokens-const tokens = tokenRelay(link.ask, tm, path.join(HOST_RUN, RUNNER_TOKEN_DIR));+freshTokenDir(HOST_RUN); // no runner's token socket outlives the host that served it+const tokens = tokenRelay(link.ask, tm);const previews = hostPreviews({ ask: link.ask });// ---------------------------------------------------------------- start@@ -435,7 +436,7 @@ const previews = hostPreviews({ ask: link.ask });mkdirSync(HOST_RUN, { recursive: true });const tokenServer = tokens.serve(path.join(HOST_RUN, HOST_TOKEN_SOCKET));await api.boot(); // settles the journals no runner holds (work 084); none on a host that never had a v4 gateway-api.rediscovered(await rediscover((id, sock) => starts.adopt(id, sock, { verify: true }).then((r) => log.info('rediscovered runner', id, r.key || 'spare'))));+api.rediscovered(await rediscover(HOST_RUN, (id, sock) => starts.adopt(id, sock, { verify: true }).then((r) => log.info('rediscovered runner', id, r.key || 'spare'))));log.info(`host ${identity.hostId} (${VERSION}) run=${HOST_RUN} launch=${LAUNCH} ${workspacesEnabled() ? 'workspaces' : 'laptop'} mode, ${runners.size} live runner(s), pool ${POOL_SIZE}`);link.dial();setInterval(fillPool, 30_000).unref();diff --git a/computer/src/host/runner-api.ts b/computer/src/host/runner-api.tsindex 96e718f7..0f4570b9 100644--- a/computer/src/host/runner-api.ts+++ b/computer/src/host/runner-api.ts@@ -25,11 +25,10 @@ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';import { mkdir, rename, writeFile } from 'node:fs/promises';import path from 'node:path';import type { RunnerApi, SessionReport } from '../protocol.js';-import { RUNNERS_DIR } from '../ipc.js';/** The suffix of every API socket; rediscover skips these. */export const API_SOCK = '.api.sock';-export const apiSocketFor = (name: string, dir = RUNNERS_DIR) => path.join(dir, `${name}${API_SOCK}`);+export const apiSocketFor = (name: string, dir: string) => path.join(dir, `${name}${API_SOCK}`);export const mintToken = () => randomBytes(32).toString('base64url');/** Stores with a write still due, flushed synchronously when the process exits. */diff --git a/computer/src/host/runner-sockets.ts b/computer/src/host/runner-sockets.tsindex 05b497b0..2483a765 100644--- a/computer/src/host/runner-sockets.ts+++ b/computer/src/host/runner-sockets.ts@@ -11,8 +11,8 @@import net from 'node:net';import path from 'node:path';import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs';-import { HOST_RUN, type HostToRunner, type RunnerSpec } from '../protocol.js';-import { RUNNERS_DIR, pidFileFor, send } from '../ipc.js';+import type { HostToRunner, RunnerSpec } from '../protocol.js';+import { type RunRoot, pidFileFor, runnersDir, secretsFor, send } from '../ipc.js';import { log } from '../log.js';import type { Telemetry } from '../telemetry/emitter.js';import type { Dimensions } from '../telemetry/envelope.js';@@ -68,7 +68,8 @@ function drop(p: string) {}}-export async function rediscover(adopt: (id: string, sock: net.Socket) => Promise<unknown>) {+export async function rediscover(run: RunRoot, adopt: (id: string, sock: net.Socket) => Promise<unknown>) {+ const RUNNERS_DIR = runnersDir(run);mkdirSync(RUNNERS_DIR, { recursive: true });const live = new Set<string>();const names = readdirSync(RUNNERS_DIR);@@ -90,7 +91,7 @@ export async function rediscover(adopt: (id: string, sock: net.Socket) => Promis}// A runner that was killed outright left its secrets behind (session-secrets.ts), named as its socket.// They are the runners' user's (0700), so removed as that user; one left behind never stops the host.- const secretsDir = path.join(HOST_RUN, 'secrets');+ const secretsDir = path.dirname(secretsFor(run, 'x'));let left: string[] = [];try {left = existsSync(secretsDir) ? readdirSync(secretsDir) : [];@@ -98,7 +99,7 @@ export async function rediscover(adopt: (id: string, sock: net.Socket) => Promislog.warn(`cannot list ${secretsDir}: ${e?.message ?? e}`);}for (const d of left.filter((d) => !live.has(d)))- await rm(path.join(secretsDir, d)).catch((e) => log.warn(`secrets of ${d} not removed: ${e?.message ?? e}`));+ await rm(secretsFor(run, d)).catch((e) => log.warn(`secrets of ${d} not removed: ${e?.message ?? e}`));return live;}diff --git a/computer/src/host/start-runner.ts b/computer/src/host/start-runner.tsindex e188dfb7..66f91b69 100644--- a/computer/src/host/start-runner.ts+++ b/computer/src/host/start-runner.ts@@ -29,7 +29,7 @@ import type {} from '../protocol.js';import type { RunnerApi } from '../protocol-api.js';import { forkDir, forkInfo, mkdirAsRunner, workspacePrepared, workspacesEnabled } from '../workspaces/index.js';-import { lines, send, socketFor } from '../ipc.js';+import { type RunRoot, lines, send, socketFor } from '../ipc.js';import { log } from '../log.js';import type { Telemetry } from '../telemetry/emitter.js';import type { Dimensions } from '../telemetry/envelope.js';@@ -71,6 +71,8 @@ export interface StartDeps {tm: Telemetry;/** How runners are launched (launch.ts): the mode, the host's environment and its release. */launch: { tm: Telemetry; mode: string; env: NodeJS.ProcessEnv; root: string };+ /** The run root runners are started under (ipc.ts). */+ run: RunRoot;version: string;pool: Pool<Runner>;/** The organization's credentials as the gateway last sent them. */@@ -80,7 +82,7 @@ export interface StartDeps {/** Work 084: the session's journal, socket and token for this runner; undefined off the API. */mint(spec: SessionSpec, runnerId: string): Promise<RunnerApi | undefined>;/** The runner's own token socket, naming the session it serves now (tokens.ts). */- serveTokens(id: string, sock: net.Socket, session: () => string | undefined): void;+ serveTokens(id: string, session: () => string | undefined): { close(): void };fillPool(): void;/** Run a fork so its workspace events join the delivery's trace. */inFork<T>(f: Dimensions, fn: () => Promise<T>): Promise<T>;@@ -108,7 +110,8 @@ export function runnerStarts(d: StartDeps) {* `first`: the delivery's credentials, sent instead of the welcome ones, since the runner starts its harness with the first it gets. */function adopt(id: string, sock: net.Socket, o: { key?: string; verify?: boolean; first?: HostCredentials; harness?: HarnessName } = {}): Promise<Runner> {const r: Runner = { id, key: o.key ?? '', sock, lastDelivery: Date.now(), connectedAt: Date.now(), calls: new Map(), harness: o.harness };- d.serveTokens(id, sock, () => r.key); // its own token socket names the session it serves now (work 080)+ const tokens = d.serveTokens(id, () => r.key); // its own token socket names the session it serves now (work 080)+ sock.once('close', () => tokens.close()); // gone with the runnerreturn new Promise((resolve, reject) => {const take = (m?: First) => {if (m?.t === 'report') (r.key = m.report.key), (r.harness ??= m.report.harness);@@ -180,7 +183,7 @@ export function runnerStarts(d: StartDeps) {const { ready: sock } = await coldStart({dir,fork: existing ? undefined : () => d.inFork(f, () => forkFor(tm, spec, f)),- start: (cwd) => launchRunner({ id, session: { ...spec, forkPath: cwd }, socket: socketFor(id), api: runnerApi && { ...runnerApi, token: '' }, version: d.version }, { ...d.launch, f }),+ start: (cwd) => launchRunner({ id, session: { ...spec, forkPath: cwd }, socket: socketFor(d.run, id), api: runnerApi && { ...runnerApi, token: '' }, version: d.version }, { ...d.launch, f }),abandon: d.exit,});if (sock.destroyed) throw new Error('runner exited while its fork was made');@@ -194,7 +197,7 @@ export function runnerStarts(d: StartDeps) {async function launchSpare() {const id = newRunnerId();await d.models.spare(id);- await launchRunner({ id, socket: socketFor(id), version: d.version }, d.launch).then((sock) => adopt(id, sock))+ await launchRunner({ id, socket: socketFor(d.run, id), version: d.version }, d.launch).then((sock) => adopt(id, sock)).catch((e) => (d.models.closed('', id), Promise.reject(e)));tm.emit('pool.spare_started', { data: { launch_mode: d.launch.mode } });}diff --git a/computer/src/host/tokens.test.ts b/computer/src/host/tokens.test.tsindex 32398ab1..2455bf56 100644--- a/computer/src/host/tokens.test.ts+++ b/computer/src/host/tokens.test.ts@@ -7,7 +7,8 @@ import { promisify } from 'node:util';import { describe, expect, it, vi } from 'vitest';import { createTelemetry } from '../telemetry/emitter.js';import type { HostToGateway } from '../protocol.js';-import { tokenRelay } from './tokens.js';+import { tokenSocketFor } from '../ipc.js';+import { freshTokenDir, tokenRelay } from './tokens.js';const run = promisify(execFile);const helper = path.resolve('bin/git-credential-slack-presence');@@ -75,15 +76,17 @@ describe('token relay', () => {it("gives each runner its own socket in a setgid directory it cannot write, gone when the runner goes", async () => {const tm = createTelemetry({ service: 'host', version: 'v', region: 'r', send: () => {} });- const dir = path.join(mkdtempSync(path.join(tmpdir(), 'tokens-')), 'runners');- const relay = tokenRelay(() => false, tm, dir);+ const root = mkdtempSync(path.join(tmpdir(), 'tokens-'));+ const relay = tokenRelay(() => false, tm);+ const dir = freshTokenDir(root);// 02750: the sockets made here keep SP_RUN's group, so runners running as another user still reach them (work 077).expect(statSync(dir).mode & 0o7777).toBe(0o2750);- const runner = new net.Socket();- relay.serveRunner('r1', runner, () => 'T1:C1:1.1');+ const serving = relay.serveRunner(root, 'r1', () => 'T1:C1:1.1');+ expect(relay.serveRunner(root, 'r1', () => 'T1:C2:2.2')).toBe(serving); // once per runnerconst sock = path.join(dir, 'r1.sock');+ expect(sock).toBe(tokenSocketFor(root, 'r1'));await vi.waitFor(() => expect(existsSync(sock)).toBe(true));- runner.destroy();+ serving.close();await vi.waitFor(() => expect(existsSync(sock)).toBe(false));});diff --git a/computer/src/host/tokens.ts b/computer/src/host/tokens.tsindex c6740eca..4e9c2cf4 100644--- a/computer/src/host/tokens.ts+++ b/computer/src/host/tokens.ts@@ -17,7 +17,7 @@ import { randomUUID } from 'node:crypto';import { chmodSync, mkdirSync, rmSync } from 'node:fs';import path from 'node:path';import type { GitHubToken, HostToGateway, TokenKind } from '../protocol.js';-import { lines } from '../ipc.js';+import { type RunRoot, lines, tokenSocketFor } from '../ipc.js';import type { Telemetry } from '../telemetry/emitter.js';export interface TokenRelay {@@ -30,22 +30,30 @@ export interface TokenRelay {* `session`: the session asking, for a runner's own socket; a `sessionKey` in the request is ignored.*/serve(socket: string, session?: () => string | undefined): net.Server;- /** A runner's own token socket in the runners' directory, for the session it serves now; closed when its socket closes. */- serveRunner(id: string, runner: net.Socket, session: () => string | undefined): void;+ /**+ * A runner's own token socket below its run root (`tokenSocketFor`); `session` is the host's word for who asks.+ * Idempotent per id; the caller closes it when the runner is gone. The directory is the caller's to make (`freshTokenDir`).+ */+ serveRunner(run: RunRoot, id: string, session: () => string | undefined): { close(): void };}/**- * `ask` sends to the gateway and returns false when it is not connected.- * `runnerDir`: where runners' own sockets go, emptied and made again here. Only the host writes there, so a session- * cannot put its own socket in another's place; 02750 keeps SP_RUN's setgid group on the sockets, so runners running- * as another user (work 077) can still reach their own.+ * Empty and make again the directory of a run root's token sockets, once at host start. Only the host writes there,+ * so a session cannot put its own socket in another's place; 02750 keeps SP_RUN's setgid group on the sockets, so+ * runners running as another user (work 077) can still reach their own.*/-export function tokenRelay(ask: (m: Extract<HostToGateway, { t: 'token' }>) => boolean, tm: Telemetry, runnerDir?: string): TokenRelay {- if (runnerDir) {- rmSync(runnerDir, { recursive: true, force: true });- mkdirSync(runnerDir, { recursive: true });- chmodSync(runnerDir, 0o2750);- }+export function freshTokenDir(run: RunRoot) {+ const dir = path.dirname(tokenSocketFor(run, 'x'));+ rmSync(dir, { recursive: true, force: true });+ mkdirSync(dir, { recursive: true });+ chmodSync(dir, 0o2750);+ return dir;+}++/** `ask` sends to the gateway and returns false when it is not connected. */+export function tokenRelay(ask: (m: Extract<HostToGateway, { t: 'token' }>) => boolean, tm: Telemetry): TokenRelay {+ /** The runners' sockets being served, by path. */+ const served = new Map<string, { close(): void }>();const waiters = new Map<string, (m: { result?: GitHubToken; error?: string }) => void>();const tokens = new Map<string, Promise<GitHubToken>>();@@ -92,10 +100,14 @@ export function tokenRelay(ask: (m: Extract<HostToGateway, { t: 'token' }>) => bconst relay: TokenRelay = {request,answer: (m) => waiters.get(m.id)?.(m),- serveRunner(id, runner, session) {- if (!runnerDir) throw new Error('no runner token directory');- const server = relay.serve(path.join(runnerDir, `${id}.sock`), session);- runner.once('close', () => server.close());+ serveRunner(run, id, session) {+ const socket = tokenSocketFor(run, id);+ const open = served.get(socket);+ if (open) return open;+ const server = relay.serve(socket, session);+ const handle = { close: () => void (served.get(socket) === handle && (served.delete(socket), server.close())) };+ served.set(socket, handle);+ return handle;},serve(socket, session) {rmSync(socket, { force: true });diff --git a/computer/src/ipc.ts b/computer/src/ipc.tsindex 3a064f76..7d0880b4 100644--- a/computer/src/ipc.ts+++ b/computer/src/ipc.ts@@ -1,9 +1,10 @@// Newline-delimited JSON over unix sockets (host ⇄ runner, helpers → host),-// and where runner sockets live on a host.+// and where a runner's sockets and files live below a run root. The layout+// below a root is the same for every root; nothing here reads the environment.import type { Socket } from 'node:net';import path from 'node:path';-import { HOST_RUN } from './protocol.js';+import { RUNNER_TOKEN_DIR } from './protocol.js';import { log } from './log.js';/** Call `on` with every JSON line arriving on `sock`. */@@ -34,14 +35,22 @@ export function send(sock: Socket | undefined, m: object) {if (sock && !sock.destroyed && sock.writable) sock.write(JSON.stringify(m) + '\n');}-export const RUNNERS_DIR = path.join(HOST_RUN, 'runners');+/** The directory a runner sees as SP_RUN: HOST_RUN itself, or its own under HOST_RUN/sandbox (work 103). */+export type RunRoot = string;+export const runnersDir = (run: RunRoot) => path.join(run, 'runners');/**- * <SP_RUN>/runners/<name>.sock, a `.pid` file next to it. The name is the+ * <run>/runners/<name>.sock, a `.pid` file next to it. The name is the* runner's id (work 069), or `keyName` of its session for runners started by* hosts before; the runner's first report says which session it serves.*/-export const socketFor = (name: string) => path.join(RUNNERS_DIR, `${name}.sock`);+export const socketFor = (run: RunRoot, name: string) => path.join(runnersDir(run), `${name}.sock`);+/** Where a runner's previews are dialed from outside its network namespace (work 103); nothing listens there yet. */+export const previewSocketFor = (run: RunRoot, name: string) => path.join(runnersDir(run), `${name}.preview.sock`);+/** A runner's own token socket (host/tokens.ts, work 080): the host knows the session from which one is asked. */+export const tokenSocketFor = (run: RunRoot, id: string) => path.join(run, RUNNER_TOKEN_DIR, `${id}.sock`);+/** A runner's secrets (runner/session-secrets.ts), named as its socket. */+export const secretsFor = (run: RunRoot, id: string) => path.join(run, 'secrets', id);/** A session key as a file name: runners before work 069, and the session's trace file. */export const keyName = (key: string) => Buffer.from(key).toString('base64url');export const pidFileFor = (socket: string) => socket.replace(/\.sock$/, '.pid');diff --git a/computer/src/runner/main.ts b/computer/src/runner/main.tsindex 6069c89d..1546c544 100644--- a/computer/src/runner/main.ts+++ b/computer/src/runner/main.ts@@ -44,8 +44,8 @@ import { SessionSecrets, redactingClient } from './session-secrets.js';import { PromptGuard } from './prompt-guard.js';import { codexBin } from '../runner-env.js';import { fakeSlack } from '../dev/fake-slack.js';-import { lines, pidFileFor, send } from '../ipc.js';-import { HOST_RUN, NOT_ASKED, RUNNER_TOKEN_DIR, isSlackSpec, type RunnerApi } from '../protocol.js';+import { lines, pidFileFor, secretsFor, send, tokenSocketFor } from '../ipc.js';+import { HOST_RUN, NOT_ASKED, isSlackSpec, type RunnerApi } from '../protocol.js';import { type AttachedApi, attachApi } from './api/attach.js';import { NullSurface } from './api/surface.js';import { RunningSubagents } from './api/running.js';@@ -95,7 +95,7 @@ const spec: RunnerSpec = JSON.parse(env.RUNNER_SPEC ?? '');let ss: Bound | undefined = spec.session;const ROOT = path.resolve(import.meta.dirname, '..', '..');// Named as the socket is: the runner's id, or its session key from a host before work 069.-const secrets = new SessionSecrets(path.join(HOST_RUN, 'secrets', path.basename(spec.socket, '.sock')));+const secrets = new SessionSecrets(secretsFor(HOST_RUN, path.basename(spec.socket, '.sock')));// Commits are authored by the initiator (sessionVars) and committed by the app identity.const sessionVars = (b: Bound) => ({ GIT_AUTHOR_NAME: b.owner.gitName, GIT_AUTHOR_EMAIL: b.owner.gitEmail, SP_SESSION_KEY: b.key });@@ -105,7 +105,7 @@ Object.assign(env, {// What bin/git-credential-slack-presence and bin/gh need to find the host: this runner's own// token socket, where the host knows which session asks (work 080).SP_RUN: HOST_RUN,- SP_TOKEN_SOCKET: path.join(HOST_RUN, RUNNER_TOKEN_DIR, path.basename(spec.socket)),+ SP_TOKEN_SOCKET: tokenSocketFor(HOST_RUN, path.basename(spec.socket, '.sock')),// bin/calvin-send-file: scripts post files into the thread (send-file-socket.ts). Not// `.sock`: the host takes every `*.sock` in the runners directory for a runner.SP_FILES_SOCKET: spec.socket.replace(/\.sock$/, '.files'),