Skip to content
TypeScript

feat(server): `t3 service protect` keeps the server alive when agents fill memory (#27239)

Julius Marminge44d508fd8b44
diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts
index 033a96693ad..2ea799d9f09 100644
--- a/apps/server/src/cli/service.test.ts
+++ b/apps/server/src/cli/service.test.ts
@@ -90,6 +90,37 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands
}),
);
+ it.effect("protect refuses root before creating any T3 directories", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
+ const baseDir = `${parent}/t3`;
+ vi.spyOn(BootService, "layer").mockReturnValue(
+ Layer.succeed(BootService.BootService, makeTestService(status).service),
+ );
+
+ const output = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
+ "protect",
+ "--base-dir",
+ baseDir,
+ ]).pipe(
+ Effect.andThen(TestConsole.logLines),
+ Effect.map((lines) => lines.join("\n")),
+ Effect.provideService(HostProcess.Environment, {}),
+ Effect.provideService(HostProcess.Platform, "linux"),
+ Effect.provideService(HostProcess.UserId, 0),
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
+ Layer.fresh(TestConsole.layer),
+ ),
+ ),
+ );
+ expect(output).toContain("without sudo");
+ expect(yield* fs.exists(baseDir)).toBe(false);
+ }),
+ );
+
// regression: #13239 a stale nvm-installed CLI reported "already using" its own version
it.effect.each(["install", "update"] as const)(
"%s names the CLI that found nothing to change",
diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts
index 97ceafd941f..62edb31d14b 100644
--- a/apps/server/src/cli/service.ts
+++ b/apps/server/src/cli/service.ts
@@ -2,12 +2,14 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Path from "effect/Path";
import * as Terminal from "effect/Terminal";
import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
import { FetchHttpClient } from "effect/http";
import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
+import * as ServiceProtection from "../cloud/serviceProtection.ts";
import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
import type * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
@@ -68,7 +70,23 @@ function formatServiceChange(
return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`;
}
-function formatServiceStatus(status: BootService.BootServiceStatus, cliVersion: string): string {
+function formatProtection(
+ protection: ServiceProtection.ServiceProtectionState | undefined,
+): ReadonlyArray<string> {
+ if (protection === undefined) return [];
+ return [
+ protection.unprotected === undefined
+ ? ` Memory protection: on${protection.setByProtect ? " (t3 service protect)" : ""}`
+ : ` Memory protection: off, ${protection.unprotected} grants none. Run \`t3 service protect\`.`,
+ ...(protection.oomScoreAdj === undefined ? [] : [` OOM score: ${protection.oomScoreAdj}`]),
+ ];
+}
+
+function formatServiceStatus(
+ status: BootService.BootServiceStatus,
+ cliVersion: string,
+ protection?: ServiceProtection.ServiceProtectionState,
+): string {
if (!status.supported) {
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
}
@@ -89,6 +107,7 @@ function formatServiceStatus(status: BootService.BootServiceStatus, cliVersion:
` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
` Unit: ${status.unitPath}`,
` Logs: ${status.logPath}`,
+ ...formatProtection(protection),
...problems,
` Next: Run \`t3 update ${installedVersion}\` to match it, or pass \`--allow-downgrade\` to \`t3 service install\` explicitly.`,
].join("\n");
@@ -98,6 +117,7 @@ function formatServiceStatus(status: BootService.BootServiceStatus, cliVersion:
` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
` Unit: ${status.unitPath}`,
` Logs: ${status.logPath}`,
+ ...formatProtection(protection),
...problems,
...(status.current ? [] : [" Next: Run `t3 service install` to repair it."]),
].join("\n");
@@ -210,12 +230,121 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
flags,
Effect.gen(function* () {
const service = yield* BootService.BootService;
- yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));
+ const path = yield* Path.Path;
+ const status = yield* service.status;
+ const protection =
+ status.installed && (yield* HostProcess.Platform) === "linux"
+ ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe(
+ Effect.provide(ProcessRunner.layer),
+ )
+ : undefined;
+ yield* Console.log(formatServiceStatus(status, packageJson.version, protection));
}),
),
),
);
+const formatDropIns = (dropIns: ReadonlyArray<ServiceProtection.DropIn>) =>
+ dropIns.map(
+ ({ path, contents }) => ` ${path}: ${contents.trimEnd().split("\n").slice(1).join(" ")}`,
+ );
+
+const confirm = (yes: boolean, message: string) =>
+ yes ? Effect.succeed(true) : Prompt.run(Prompt.Confirm({ message, initial: false }));
+
+const serviceProtectCommand = Command.make("protect", {
+ ...projectLocationFlags,
+ undo: Flag.Boolean("undo").pipe(
+ Flag.withDescription("Remove the protection this command set up."),
+ Flag.withDefault(false),
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withDescription("Answer yes to every question, including SSH and Tailscale."),
+ Flag.withDefault(false),
+ ),
+}).pipe(
+ Command.withDescription(
+ "Protect the T3 Code server from agents under memory pressure (Linux with systemd). Asks for sudo.",
+ ),
+ Command.withHandler((flags) =>
+ Effect.gen(function* () {
+ const unsupported = "Service protection needs Linux with systemd.";
+ if ((yield* HostProcess.Platform) !== "linux") return yield* Console.log(unsupported);
+ // Before resolving config, which creates T3 directories that root would then own.
+ if ((yield* HostProcess.UserId) === 0) {
+ return yield* Console.log(
+ "Run `t3 service protect` as the user that runs T3 Code, without sudo. It asks for sudo when it needs root.",
+ );
+ }
+ return yield* runServiceCommand(
+ flags,
+ Effect.gen(function* () {
+ const uid = yield* HostProcess.UserId;
+ const remote = yield* ServiceProtection.detectRemoteAccessUnits;
+ const { unitPath } = yield* (yield* BootService.BootService).status;
+ if (uid === undefined || remote === undefined || unitPath === "") {
+ return yield* Console.log(unsupported);
+ }
+ const userUnitDir = (yield* Path.Path).dirname(unitPath);
+
+ if (flags.undo) {
+ const installed = yield* ServiceProtection.installedProtection(
+ ServiceProtection.protectionPlan({
+ uid,
+ userUnitDir,
+ remoteAccessUnits: ServiceProtection.REMOTE_ACCESS_UNITS,
+ }),
+ );
+ if (installed === undefined) {
+ return yield* Console.log("T3 Code service protection is not set up.");
+ }
+ yield* Console.log(
+ [
+ "Removes:",
+ ...[...installed.system, ...installed.user, installed.managerDefaults].map(
+ ({ path, shared }) =>
+ ` ${path}${shared === true ? " (kept while another user is protected)" : ""}`,
+ ),
+ ].join("\n"),
+ );
+ if (!(yield* confirm(flags.yes, "Remove T3 Code service protection?"))) return;
+ yield* ServiceProtection.removeProtection(installed);
+ return yield* Console.log(
+ "Removed T3 Code service protection. The server's OOM score returns to normal after `t3 service restart`.",
+ );
+ }
+
+ const names = remote.map((unit) => unit.replace(/\.service$/, "")).join(" and ");
+ const protectRemote =
+ remote.length > 0 &&
+ (yield* confirm(
+ flags.yes,
+ `Also protect ${names} so you can still reach this machine under memory pressure?`,
+ ));
+ const plan = ServiceProtection.protectionPlan({
+ uid,
+ userUnitDir,
+ remoteAccessUnits: protectRemote ? remote : [],
+ });
+ yield* Console.log(
+ [
+ "As root, through sudo:",
+ ...formatDropIns(plan.system),
+ "As you:",
+ ...formatDropIns([plan.managerDefaults, ...plan.user]),
+ ].join("\n"),
+ );
+ if (!(yield* confirm(flags.yes, "Apply these settings?"))) return;
+ yield* ServiceProtection.applyProtection(plan);
+ yield* Console.log(
+ "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`.",
+ );
+ }).pipe(Effect.provide(ProcessRunner.layer)),
+ );
+ }),
+ ),
+);
+
export type ServiceOnboardingOutcome = "ready" | "pending" | "skipped";
export const offerServiceDuringOnboarding = Effect.gen(function* () {
@@ -305,6 +434,7 @@ export const serviceCommand = Command.make("service").pipe(
serviceRestartCommand,
serviceUninstallCommand,
serviceStatusCommand,
+ serviceProtectCommand,
serviceUpdateCommand,
]),
);
diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts
index 5491328a304..2edd1106480 100644
--- a/apps/server/src/cloud/bootService.test.ts
+++ b/apps/server/src/cloud/bootService.test.ts
@@ -56,7 +56,13 @@ it("protects the server unit from agents under CPU and memory pressure", () => {
unitPath: "/home/theo/.config/systemd/user/t3code.service",
});
const service = unit.slice(unit.indexOf("[Service]"), unit.indexOf("[Install]"));
- for (const line of ["CPUWeight=1000", "IOWeight=1000", "MemoryLow=1536M", "OOMPolicy=continue"]) {
+ for (const line of [
+ "CPUWeight=1000",
+ "IOWeight=1000",
+ "MemoryLow=1536M",
+ "OOMScoreAdjust=100",
+ "OOMPolicy=continue",
+ ]) {
expect(service.split("\n")).toContain(line);
}
});
diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts
index 5206992f269..948d780c867 100644
--- a/apps/server/src/cloud/bootService.ts
+++ b/apps/server/src/cloud/bootService.ts
@@ -116,6 +116,9 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
// Reclaim takes the agents' unprotected pages first. The kernel caps this at the
// protection of user.slice and [email protected], which only root can grant.
"MemoryLow=1536M",
+ // A user manager's own score, the lowest it may set: below its other services (200) and agents (800).
+ // `t3 service protect` lowers it further through a drop-in.
+ "OOMScoreAdjust=100",
// systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is.
"ManagedOOMPreference=avoid",
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
diff --git a/apps/server/src/cloud/serviceProtection.test.ts b/apps/server/src/cloud/serviceProtection.test.ts
new file mode 100644
index 00000000000..b2e4a1506cb
--- /dev/null
+++ b/apps/server/src/cloud/serviceProtection.test.ts
@@ -0,0 +1,265 @@
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeChildProcess from "node:child_process";
+import * as NodeFS from "node:fs";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { describe, expect, it } from "@effect/vitest";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Sink from "effect/Sink";
+import * as Stream from "effect/Stream";
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+
+import * as ProcessRunner from "../processRunner.ts";
+import * as ServiceProtection from "./serviceProtection.ts";
+
+const temporaryDirectory = () =>
+ NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-service-protection-"));
+
+describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("renderPrivilegedScript", () => {
+ it("writes and removes only its drop-ins and gives running main processes their score", () => {
+ const root = temporaryDirectory();
+ const target = NodeChildProcess.spawn("sleep", ["60"], { stdio: "ignore" });
+ try {
+ const systemUnitDir = NodePath.join(root, "system");
+ const plan = (uid: number, remoteAccessUnits: ReadonlyArray<string>) =>
+ ServiceProtection.protectionPlan({
+ uid,
+ userUnitDir: "/home/theo/.config/systemd/user",
+ remoteAccessUnits,
+ systemUnitDir,
+ });
+ const theo = plan(1000, ["tailscaled.service", "ssh.service"]);
+ expect(theo.system.find((dropIn) => dropIn.unit === "[email protected]")?.contents).toBe(
+ "[Service]\nMemoryLow=2G\nOOMScoreAdjust=-900\n",
+ );
+ expect(theo.managerDefaults.path).toBe(
+ "/home/theo/.config/systemd/user.conf.d/90-t3code-protect.conf",
+ );
+ expect(theo.oomUnits).toEqual(["[email protected]", "tailscaled.service", "ssh.service"]);
+
+ const unrelated = NodePath.join(systemUnitDir, "ssh.service.d", "50-admin.conf");
+ NodeFS.mkdirSync(NodePath.dirname(unrelated), { recursive: true });
+ NodeFS.writeFileSync(unrelated, "[Service]\nNice=1\n");
+ const bin = NodePath.join(root, "bin");
+ NodeFS.mkdirSync(bin);
+ // Raising a score needs no privilege, so the test's own child stands in for a main process.
+ NodeFS.writeFileSync(
+ NodePath.join(bin, "systemctl"),
+ [
+ "#!/bin/sh",
+ 'echo "$*" >>"$CALLS"',
+ 'case "$*" in',
+ ' *MainPID*) echo "$TARGET_PID" ;;',
+ " *OOMScoreAdjust*) echo 900 ;;",
+ "esac",
+ "",
+ ].join("\n"),
+ { mode: 0o755 },
+ );
+ const calls = NodePath.join(root, "calls");
+ const runScript = (protection: ServiceProtection.ProtectionPlan, mode: "apply" | "undo") => {
+ const result = NodeChildProcess.spawnSync(
+ "/bin/sh",
+ ["-c", ServiceProtection.renderPrivilegedScript(protection, mode)],
+ {
+ encoding: "utf8",
+ env: {
+ PATH: `${bin}:/usr/bin:/bin`,
+ CALLS: calls,
+ TARGET_PID: String(target.pid),
+ },
+ },
+ );
+ expect(result.stderr).toBe("");
+ expect(result.status).toBe(0);
+ };
+ const exists = (unit: string) =>
+ NodeFS.existsSync(NodePath.join(systemUnitDir, `${unit}.d`, "90-t3code-protect.conf"));
+
+ runScript(theo, "apply");
+ runScript(plan(1001, []), "apply");
+ for (const { path, contents } of theo.system) {
+ expect(NodeFS.readFileSync(path, "utf8")).toBe(contents);
+ }
+ expect(NodeFS.readFileSync(`/proc/${target.pid}/oom_score_adj`, "utf8").trim()).toBe("900");
+ expect(NodeFS.readFileSync(calls, "utf8").split("\n")[0]).toBe("daemon-reload");
+
+ // Undo removes every drop-in a user could own, and keeps shared ones while another user is protected.
+ const undo = (uid: number) => plan(uid, ServiceProtection.REMOTE_ACCESS_UNITS);
+ runScript(undo(1000), "undo");
+ expect(["user-1000.slice", "[email protected]"].some(exists)).toBe(false);
+ expect(
+ ["user.slice", "system.slice", "tailscaled.service", "ssh.service"].every(exists),
+ ).toBe(true);
+
+ runScript(undo(1001), "undo");
+ for (const { path } of undo(1001).system) expect(NodeFS.existsSync(path)).toBe(false);
+ expect(NodeFS.existsSync(NodePath.join(systemUnitDir, "user.slice.d"))).toBe(false);
+ expect(NodeFS.readFileSync(unrelated, "utf8")).toBe("[Service]\nNice=1\n");
+ } finally {
+ target.kill();
+ NodeFS.rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
+
+it.each([
+ [
+ "Debian, where sshd.service aliases ssh.service",
+ "Id=tailscaled.service\nLoadState=loaded\n\nId=ssh.service\nLoadState=loaded\n\nId=ssh.service\nLoadState=loaded\n",
+ ["tailscaled.service", "ssh.service"],
+ ],
+ [
+ "Fedora without Tailscale",
+ "Id=tailscaled.service\nLoadState=not-found\n\nId=ssh.service\nLoadState=not-found\n\nId=sshd.service\nLoadState=loaded\n",
+ ["sshd.service"],
+ ],
+])("finds remote-access services on %s", (_, shown, expected) => {
+ expect(ServiceProtection.loadedRemoteAccessUnits(shown)).toEqual(expected);
+});
+
+const fakeSudo = (exitCode: number, onRun: () => void) =>
+ ChildProcessSpawner.make((command) =>
+ Effect.gen(function* () {
+ if (command._tag !== "StandardCommand" || command.command !== "sudo") {
+ return yield* Effect.die("Unexpected command");
+ }
+ onRun();
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(123),
+ stdout: Stream.empty,
+ stderr: Stream.empty,
+ all: Stream.empty,
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ });
+ }),
+ );
+
+const runner = (stdout: string) =>
+ ProcessRunner.ProcessRunner.of({
+ run: () =>
+ Effect.succeed({
+ stdout,
+ stderr: "",
+ code: ChildProcessSpawner.ExitCode(0),
+ timedOut: false,
+ stdoutTruncated: false,
+ stderrTruncated: false,
+ stdoutInvalidUtf8: false,
+ stderrInvalidUtf8: false,
+ }),
+ });
+
+it.effect("lowers no score before the manager default is in place, and undoes in reverse", () => {
+ const home = temporaryDirectory();
+ return Effect.gen(function* () {
+ const plan = ServiceProtection.protectionPlan({
+ uid: 1000,
+ userUnitDir: NodePath.join(home, ".config", "systemd", "user"),
+ remoteAccessUnits: [],
+ systemUnitDir: NodePath.join(home, "system"),
+ });
+ const managerDropIn = plan.system.find(({ unit }) => unit === "[email protected]")!.path;
+ const present = () => ({
+ managerDefaults: NodeFS.existsSync(plan.managerDefaults.path),
+ user: plan.user.filter(({ path }) => NodeFS.existsSync(path)).length,
+ });
+ const withSudo = <A, E, R>(
+ effect: Effect.Effect<A, E, R>,
+ exitCode: number,
+ writesManagerDropIn = false,
+ ) => {
+ let atSudo: ReturnType<typeof present> | undefined;
+ return effect.pipe(
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ fakeSudo(exitCode, () => {
+ atSudo = present();
+ if (writesManagerDropIn) {
+ NodeFS.mkdirSync(NodePath.dirname(managerDropIn), { recursive: true });
+ NodeFS.writeFileSync(managerDropIn, "[Service]\nOOMScoreAdjust=-900\n");
+ }
+ }),
+ ),
+ Effect.exit,
+ Effect.map((exit) => ({ exit, atSudo })),
+ );
+ };
+ const refused = yield* withSudo(ServiceProtection.applyProtection(plan), 1);
+ expect(refused.exit._tag).toBe("Failure");
+ expect(refused.atSudo).toEqual({ managerDefaults: true, user: 0 });
+ expect(present()).toEqual({ managerDefaults: false, user: 0 });
+
+ // Failing after it lowered the manager, sudo must leave the manager default in place.
+ const partial = yield* withSudo(ServiceProtection.applyProtection(plan), 1, true);
+ expect(partial.exit._tag).toBe("Failure");
+ expect(present()).toEqual({ managerDefaults: true, user: 0 });
+ NodeFS.rmSync(plan.managerDefaults.path);
+ NodeFS.rmSync(managerDropIn);
+
+ const applied = yield* withSudo(ServiceProtection.applyProtection(plan), 0);
+ expect(applied.atSudo).toEqual({ managerDefaults: true, user: 0 });
+ expect(present()).toEqual({ managerDefaults: true, user: plan.user.length });
+
+ const removed = yield* withSudo(ServiceProtection.removeProtection(plan), 0);
+ expect(removed.atSudo).toEqual({ managerDefaults: true, user: 0 });
+ expect(present()).toEqual({ managerDefaults: false, user: 0 });
+ }).pipe(
+ Effect.ensuring(Effect.sync(() => NodeFS.rmSync(home, { recursive: true, force: true }))),
+ Effect.provideService(ProcessRunner.ProcessRunner, runner("")),
+ Effect.provide(NodeServices.layer),
+ );
+});
+
+it.effect("counts memory.min as protection and names the first cgroup that grants none", () => {
+ const root = temporaryDirectory();
+ const controlGroup = [
+ "user.slice",
+ "user-1000.slice",
+ "app.slice",
+ "t3code.service",
+ ];
+ const write = (depth: number, file: string, value: string) => {
+ const directory = NodePath.join(root, ...controlGroup.slice(0, depth));
+ NodeFS.mkdirSync(directory, { recursive: true });
+ NodeFS.writeFileSync(NodePath.join(directory, file), `${value}\n`);
+ };
+ write(1, "memory.low", "0");
+ write(1, "memory.min", "805306368");
+ write(2, "memory.low", "2147483648");
+ write(3, "memory.low", "2147483648");
+ write(4, "memory.low", "0");
+ write(4, "memory.min", "0");
+ write(5, "memory.low", "1610612736");
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const read = ServiceProtection.readProtection("/home/theo/.config/systemd/user").pipe(
+ Effect.provideService(FileSystem.FileSystem, {
+ ...fs,
+ readFileString: (path, encoding) =>
+ fs.readFileString(path.replace("/sys/fs/cgroup", root), encoding),
+ }),
+ );
+ expect((yield* read)?.unprotected).toBe("app.slice");
+ write(4, "memory.low", "1610612736");
+ expect((yield* read)?.unprotected).toBeUndefined();
+ }).pipe(
+ Effect.ensuring(Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true }))),
+ Effect.provideService(
+ ProcessRunner.ProcessRunner,
+ runner(`ControlGroup=/${controlGroup.join("/")}\nMainPID=0\n`),
+ ),
+ Effect.provide(NodeServices.layer),
+ );
+});
diff --git a/apps/server/src/cloud/serviceProtection.ts b/apps/server/src/cloud/serviceProtection.ts
new file mode 100644
index 00000000000..b23cd36e3a5
--- /dev/null
+++ b/apps/server/src/cloud/serviceProtection.ts
@@ -0,0 +1,342 @@
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Option from "effect/Option";
+import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
+import * as ChildProcess from "effect/process/ChildProcess";
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+
+import * as ProcessRunner from "../processRunner.ts";
+import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts";
+
+const PROTECT_DROP_IN = "90-t3code-protect.conf";
+const SYSTEM_UNIT_DIR = "/etc/systemd/system";
+export const REMOTE_ACCESS_UNITS = ["tailscaled.service", "ssh.service", "sshd.service"];
+
+// Covers app.slice (the server's 1536M) and init.scope (the user manager's 256M).
+const USER_CHAIN_LOW = "MemoryLow=2G";
+// Near the floor, but unlike -1000 the kernel can still kill it as a last resort.
+const PROTECTED_OOM_SCORE = "OOMScoreAdjust=-900";
+
+export interface DropIn {
+ readonly unit: string;
+ readonly path: string;
+ readonly contents: string;
+ /** Host-wide, so undo keeps it while another user's protection remains. */
+ readonly shared?: boolean;
+}
+
+export interface ProtectionPlan {
+ readonly systemUnitDir: string;
+ /** Written through sudo. */
+ readonly system: ReadonlyArray<DropIn>;
+ /**
+ * Written before the manager's own score drops. Unset, a user manager hands
+ * its services its own score plus 100: -800 once it runs at -900.
+ */
+ readonly managerDefaults: DropIn;
+ readonly user: ReadonlyArray<DropIn>;
+ /** System units whose running main process takes its configured OOM score at once. */
+ readonly oomUnits: ReadonlyArray<string>;
+}
+
+const dropIn = (
+ directory: string,
+ unit: string,
+ section: string,
+ properties: ReadonlyArray<string>,
+ shared = false,
+): DropIn => ({
+ unit,
+ path: `${directory}/${unit}.d/${PROTECT_DROP_IN}`,
+ contents: [`[${section}]`, ...properties, ""].join("\n"),
+ ...(shared ? { shared } : {}),
+});
+
+/**
+ * Memory protection only reaches the server when every ancestor cgroup grants
+ * it, and only root can grant it on user.slice and the user manager.
+ */
+export function protectionPlan(input: {
+ readonly uid: number;
+ readonly userUnitDir: string;
+ readonly remoteAccessUnits: ReadonlyArray<string>;
+ readonly systemUnitDir?: string;
+}): ProtectionPlan {
+ const manager = `user@${input.uid}.service`;
+ const remote = input.remoteAccessUnits;
+ const systemUnitDir = input.systemUnitDir ?? SYSTEM_UNIT_DIR;
+ const system = (unit: string, section: string, properties: ReadonlyArray<string>) =>
+ dropIn(systemUnitDir, unit, section, properties);
+ const shared = (unit: string, section: string, properties: ReadonlyArray<string>) =>
+ dropIn(systemUnitDir, unit, section, properties, true);
+ const user = (unit: string, section: string, properties: ReadonlyArray<string>) =>
+ dropIn(input.userUnitDir, unit, section, properties);
+ return {
+ systemUnitDir,
+ system: [
+ shared("user.slice", "Slice", [USER_CHAIN_LOW]),
+ system(`user-${input.uid}.slice`, "Slice", [USER_CHAIN_LOW]),
+ system(manager, "Service", [USER_CHAIN_LOW, PROTECTED_OOM_SCORE]),
+ ...(remote.length > 0 ? [shared("system.slice", "Slice", ["MemoryLow=512M"])] : []),
+ ...remote.map((unit) => shared(unit, "Service", ["MemoryLow=256M", PROTECTED_OOM_SCORE])),
+ ],
+ managerDefaults: {
+ unit: "user.conf",
+ path: `${input.userUnitDir.replace(/\/user$/, "")}/user.conf.d/${PROTECT_DROP_IN}`,
+ contents: "[Manager]\nDefaultOOMScoreAdjust=200\n",
+ },
+ user: [
+ user("app.slice", "Slice", ["MemoryLow=1536M"]),
+ user("init.scope", "Scope", ["MemoryLow=256M"]),
+ user(BOOT_SERVICE_UNIT_FILE, "Service", [PROTECTED_OOM_SCORE]),
+ ],
+ oomUnits: [manager, ...remote],
+ };
+}
+
+const quoteShell = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
+const directoryOf = (file: string) => file.slice(0, file.lastIndexOf("/"));
+
+export function renderPrivilegedScript(plan: ProtectionPlan, mode: "apply" | "undo"): string {
+ const lines = ["set -e"];
+ const remove = (dropIns: ReadonlyArray<DropIn>, indent = "") => {
+ for (const { path } of dropIns) {
+ lines.push(
+ `${indent}rm -f ${quoteShell(path)}`,
+ `${indent}rmdir ${quoteShell(directoryOf(path))} 2>/dev/null || true`,
+ );
+ }
+ };
+ if (mode === "apply") {
+ for (const { path, contents } of plan.system) {
+ lines.push(
+ `mkdir -p ${quoteShell(directoryOf(path))}`,
+ `cat >${quoteShell(path)} <<'T3CODE_PROTECT'`,
+ contents.trimEnd(),
+ "T3CODE_PROTECT",
+ );
+ }
+ } else {
+ remove(plan.system.filter((dropIn) => dropIn.shared !== true));
+ const otherUsers = `${quoteShell(plan.systemUnitDir)}/user@*.service.d/${PROTECT_DROP_IN}`;
+ lines.push(`set -- ${otherUsers}`, 'if [ ! -e "$1" ]; then');
+ remove(
+ plan.system.filter((dropIn) => dropIn.shared === true),
+ " ",
+ );
+ lines.push("fi");
+ }
+ lines.push(
+ "systemctl daemon-reload",
+ // OOMScoreAdjust applies at exec; this gives running main processes the configured score.
+ `for unit in ${plan.oomUnits.map(quoteShell).join(" ")}; do`,
+ ' pid=$(systemctl show --property=MainPID --value "$unit")',
+ ' if [ "${pid:-0}" -gt 0 ]; then',
+ ' systemctl show --property=OOMScoreAdjust --value "$unit" >"/proc/$pid/oom_score_adj" || true',
+ " fi",
+ "done",
+ "",
+ );
+ return lines.join("\n");
+}
+
+export class ServiceProtectionError extends Schema.TaggedError<ServiceProtectionError>()(
+ "ServiceProtectionError",
+ {
+ step: Schema.String,
+ exitCode: Schema.optional(Schema.Number),
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return this.exitCode === undefined
+ ? `Could not ${this.step}.`
+ : `Could not ${this.step} (exit code ${this.exitCode}).`;
+ }
+}
+
+function parseUnits(text: string): Array<Map<string, string>> {
+ return text
+ .split(/\n\s*\n/)
+ .map(
+ (block) =>
+ new Map(
+ block
+ .split("\n")
+ .filter((line) => line.includes("="))
+ .map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]),
+ ),
+ )
+ .filter((values) => values.size > 0);
+}
+
+/** Loaded remote-access units by canonical name, so an alias such as sshd.service counts once. */
+export function loadedRemoteAccessUnits(systemctlShow: string): ReadonlyArray<string> {
+ const units = parseUnits(systemctlShow)
+ .filter((values) => values.get("LoadState") === "loaded")
+ .map((values) => values.get("Id") ?? "")
+ .filter((id) => REMOTE_ACCESS_UNITS.includes(id));
+ return [...new Set(units)];
+}
+
+const run = Effect.fn("ServiceProtection.run")(function* (
+ step: string,
+ command: string,
+ args: ReadonlyArray<string>,
+) {
+ const runner = yield* ProcessRunner.ProcessRunner;
+ const result = yield* runner
+ .run({ command, args, timeout: "30 seconds" })
+ .pipe(Effect.mapError((cause) => new ServiceProtectionError({ step, cause })));
+ if (result.code !== 0) {
+ return yield* new ServiceProtectionError({ step, exitCode: Number(result.code) });
+ }
+ return result.stdout;
+});
+
+const userSettingsError = (cause: unknown) =>
+ new ServiceProtectionError({ step: "change systemd user settings", cause });
+
+/** Undefined when there is no systemd system manager to ask. */
+export const detectRemoteAccessUnits = run("list remote-access services", "systemctl", [
+ "show",
+ "--property=Id,LoadState",
+ ...REMOTE_ACCESS_UNITS,
+]).pipe(
+ Effect.map(loadedRemoteAccessUnits),
+ Effect.option,
+ Effect.map(Option.getOrUndefined),
+ Effect.withSpan("ServiceProtection.detectRemoteAccessUnits"),
+);
+
+const reloadUserManager = run("reload systemd user units", "systemctl", [
+ "--user",
+ "daemon-reload",
+]);
+
+const writeDropIns = Effect.fn("ServiceProtection.writeDropIns")(function* (
+ dropIns: ReadonlyArray<DropIn>,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ for (const { path, contents } of dropIns) {
+ yield* fs.makeDirectory(directoryOf(path), { recursive: true });
+ yield* fs.writeFileString(path, contents);
+ }
+}, Effect.mapError(userSettingsError));
+
+const removeDropIns = Effect.fn("ServiceProtection.removeDropIns")(function* (
+ dropIns: ReadonlyArray<DropIn>,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ for (const { path } of dropIns) {
+ yield* fs.remove(path, { force: true });
+ yield* fs.remove(directoryOf(path)).pipe(Effect.ignore);
+ }
+}, Effect.mapError(userSettingsError));
+
+const runPrivileged = Effect.fn("ServiceProtection.runPrivileged")(function* (script: string) {
+ const step = "change the system's service settings";
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const exitCode = yield* spawner
+ .exitCode(
+ ChildProcess.make("sudo", ["/bin/sh", "-c", script], {
+ stdin: "inherit",
+ stdout: "inherit",
+ stderr: "inherit",
+ }),
+ )
+ .pipe(Effect.mapError((cause) => new ServiceProtectionError({ step, cause })));
+ if (exitCode !== 0) {
+ return yield* new ServiceProtectionError({ step, exitCode: Number(exitCode) });
+ }
+});
+
+export const applyProtection = Effect.fn("ServiceProtection.apply")(function* (
+ plan: ProtectionPlan,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const hadManagerDefaults = yield* fs
+ .exists(plan.managerDefaults.path)
+ .pipe(Effect.orElseSucceed(() => false));
+ yield* writeDropIns([plan.managerDefaults]);
+ // A partial run may already have lowered the manager; its default must then stay.
+ const manager = plan.system.find(({ unit }) => unit.startsWith("user@"));
+ const rollBack = Effect.gen(function* () {
+ if (hadManagerDefaults) return;
+ if (manager !== undefined && (yield* fs.exists(manager.path))) return;
+ yield* removeDropIns([plan.managerDefaults]);
+ }).pipe(Effect.ignore);
+ yield* runPrivileged(renderPrivilegedScript(plan, "apply")).pipe(Effect.tapError(() => rollBack));
+ yield* writeDropIns(plan.user);
+ yield* reloadUserManager;
+});
+
+export const removeProtection = Effect.fn("ServiceProtection.remove")(function* (
+ plan: ProtectionPlan,
+) {
+ yield* removeDropIns(plan.user);
+ yield* reloadUserManager;
+ if (plan.system.length > 0) yield* runPrivileged(renderPrivilegedScript(plan, "undo"));
+ yield* removeDropIns([plan.managerDefaults]);
+ yield* reloadUserManager;
+});
+
+/** The plan narrowed to drop-ins that exist, for undo. */
+export const installedProtection = Effect.fn("ServiceProtection.installed")(function* (
+ plan: ProtectionPlan,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const exists = (dropIn: DropIn) => fs.exists(dropIn.path).pipe(Effect.orElseSucceed(() => false));
+ const system = yield* Effect.filter(plan.system, exists);
+ const user = yield* Effect.filter(plan.user, exists);
+ const managerDefaults = yield* exists(plan.managerDefaults);
+ return system.length + user.length === 0 && !managerDefaults
+ ? undefined
+ : { ...plan, system, user };
+});
+
+export interface ServiceProtectionState {
+ /** The first cgroup from the top that grants the server no memory protection. */
+ readonly unprotected: string | undefined;
+ readonly oomScoreAdj: number | undefined;
+ readonly setByProtect: boolean;
+}
+
+/** Reads what the kernel applies to the running service, whoever configured it. */
+export const readProtection = Effect.fn("ServiceProtection.read")(function* (userUnitDir: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const shown = yield* run("read the service's cgroup", "systemctl", [
+ "--user",
+ "show",
+ BOOT_SERVICE_UNIT_FILE,
+ "--property=ControlGroup,MainPID",
+ ]).pipe(Effect.option);
+ if (Option.isNone(shown)) return undefined;
+ const values = parseUnits(shown.value)[0] ?? new Map<string, string>();
+ const controlGroup = (values.get("ControlGroup") ?? "").split("/").filter(Boolean);
+ if (controlGroup.length === 0) return undefined;
+ const read = (file: string) =>
+ fs.readFileString(file).pipe(
+ Effect.map((text) => text.trim()),
+ Effect.orElseSucceed(() => ""),
+ );
+ let unprotected: string | undefined;
+ const grants = (value: string) => value !== "" && value !== "0";
+ for (let depth = 1; depth <= controlGroup.length && unprotected === undefined; depth++) {
+ const directory = path.join("/sys/fs/cgroup", ...controlGroup.slice(0, depth));
+ const low = yield* read(path.join(directory, "memory.low"));
+ const min = yield* read(path.join(directory, "memory.min"));
+ if (!grants(low) && !grants(min)) unprotected = controlGroup[depth - 1];
+ }
+ const pid = Number(values.get("MainPID") ?? 0);
+ const score = pid > 0 ? yield* read(`/proc/${pid}/oom_score_adj`) : "";
+ return {
+ unprotected,
+ oomScoreAdj: score === "" ? undefined : Number(score),
+ setByProtect: yield* fs
+ .exists(path.join(userUnitDir, `${BOOT_SERVICE_UNIT_FILE}.d`, PROTECT_DROP_IN))
+ .pipe(Effect.orElseSucceed(() => false)),
+ } satisfies ServiceProtectionState;
+});
diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts
index 78097b761cb..6f3e86a7501 100644
--- a/apps/server/src/preview/ServerBrowser.ts
+++ b/apps/server/src/preview/ServerBrowser.ts
@@ -43,6 +43,7 @@ import {
SERVER_BROWSER_AUTOMATION_CLIENT_ID,
type PreviewAppearancePreference,
} from "@t3tools/contracts";
+import { AgentScope, agentScopeLauncherScript } from "@t3tools/shared/AgentScope";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import { resolvePreviewViewport } from "@t3tools/shared/previewViewport";
@@ -460,6 +461,8 @@ const make = Effect.gen(function* () {
const runPromise = Effect.runPromiseWith(yield* Effect.context<never>());
const launchServices = yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();
const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND);
+ const agentScope = yield* AgentScope;
+ const launchersDir = NodePath.join(config.stateDir, "server-browser", "launchers");
const tabs = new Map<string, ServerTab>();
const pendingTabs = new Map<string, Promise<ServerTab>>();
@@ -473,6 +476,17 @@ const make = Effect.gen(function* () {
const contexts = new ServerBrowserContexts({
profilesDir: NodePath.join(config.stateDir, "server-browser", "profiles"),
executable: () => runPromise(previewBrowser.executable),
+ // An agent scope keeps Chrome out of the server's memory protection and OOM score.
+ launcher: async (executable) => {
+ const launch = await runPromise(
+ agentScope.wrap({ command: executable, args: [], name: "preview-browser" }),
+ );
+ if (launch.command === executable) return undefined;
+ await NodeFSP.mkdir(launchersDir, { recursive: true });
+ const launcher = NodePath.join(launchersDir, NodeCrypto.randomUUID());
+ await NodeFSP.writeFile(launcher, agentScopeLauncherScript(launch), { mode: 0o700 });
+ return { path: launcher, release: () => NodeFSP.rm(launcher, { force: true }) };
+ },
// Playwright's launch error drops Chrome's own output; its sandbox note survives.
diagnose: (executable, cause) =>
Effect.runPromiseWith(launchServices)(
diff --git a/apps/server/src/preview/ServerBrowserContexts.test.ts b/apps/server/src/preview/ServerBrowserContexts.test.ts
index 7a3babd0dcc..3cab864de54 100644
--- a/apps/server/src/preview/ServerBrowserContexts.test.ts
+++ b/apps/server/src/preview/ServerBrowserContexts.test.ts
@@ -55,6 +55,17 @@ const options = () => ({
env: {},
});
+const withLauncher = () => {
+ const release = vi.fn(async () => {});
+ return {
+ release,
+ configuration: {
+ ...options(),
+ launcher: vi.fn(async (executable: string) => ({ path: `${executable}-launcher`, release })),
+ },
+ };
+};
+
beforeEach(() => {
launches.launch.mockReset();
launches.persistent.mockReset();
@@ -66,19 +77,29 @@ describe("ServerBrowserContexts", () => {
it("lazily shares one browser across concurrent isolated sessions and reuses each context", async () => {
const browser = makeBrowser();
const launch = Promise.withResolvers<Browser>();
- launches.launch.mockReturnValue(launch.promise);
- const configuration = options();
+ const started = Promise.withResolvers<void>();
+ launches.launch.mockImplementation(() => {
+ started.resolve();
+ return launch.promise;
+ });
+ const { configuration, release } = withLauncher();
const pool = new ServerBrowserContexts(configuration);
expect(configuration.executable).not.toHaveBeenCalled();
const first = pool.contextFor("default", "agent-a");
const again = pool.contextFor("default", "agent-a");
const second = pool.contextFor("default", "agent-b");
const incognito = pool.contextFor(INCOGNITO_BROWSER_PROFILE_ID);
+ await started.promise;
+ // Playwright may retry the same path until the launch settles.
+ expect(release).not.toHaveBeenCalled();
launch.resolve(browser as unknown as Browser);
const [a, reused, b, privateContext] = await Promise.all([first, again, second, incognito]);
+ expect(release).toHaveBeenCalledTimes(1);
expect(a).toBe(reused);
expect(new Set([a, b, privateContext]).size).toBe(3);
- expect(launches.launch).toHaveBeenCalledTimes(1);
+ expect(launches.launch).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ executablePath: "/test/chromium-launcher" }),
+ );
expect(launches.persistent).not.toHaveBeenCalled();
expect(browser.newContext).toHaveBeenCalledWith({
viewport: { width: 1280, height: 800 },
@@ -94,19 +115,44 @@ describe("ServerBrowserContexts", () => {
const browser = makeBrowser();
launches.persistent.mockResolvedValue(human as unknown as BrowserContext);
launches.launch.mockResolvedValue(browser as unknown as Browser);
- const pool = new ServerBrowserContexts(options());
+ const { configuration, release } = withLauncher();
+ const pool = new ServerBrowserContexts(configuration);
const persistent = await pool.contextFor("work/team");
expect(await pool.contextFor("work/team")).toBe(persistent);
expect(await pool.contextFor("work/team", "agent")).not.toBe(persistent);
expect(launches.persistent).toHaveBeenCalledExactlyOnceWith(
"/test/profiles/work%2Fteam",
- expect.objectContaining({ chromiumSandbox: true, executablePath: "/test/chromium" }),
+ expect.objectContaining({ chromiumSandbox: true, executablePath: "/test/chromium-launcher" }),
);
+ expect(release).toHaveBeenCalledTimes(2);
expect(launches.mkdir).toHaveBeenCalledWith("/test/profiles/work%2Fteam", { recursive: true });
await pool.close();
expect(human.close).toHaveBeenCalledTimes(1);
});
+ it("diagnoses a launcher failure against the real executable", async () => {
+ const diagnosed = new Error("diagnosed");
+ const diagnose = vi.fn(async () => diagnosed);
+ const pool = new ServerBrowserContexts({
+ ...options(),
+ diagnose,
+ launcher: vi.fn(async () => {
+ throw new Error("EACCES");
+ }),
+ });
+ await expect(pool.contextFor("default", "agent")).rejects.toBe(diagnosed);
+ expect(diagnose).toHaveBeenCalledExactlyOnceWith("/test/chromium", expect.any(Error));
+ expect(launches.launch).not.toHaveBeenCalled();
+ });
+
+ it("creates no launcher for a profile whose storage cannot be created", async () => {
+ launches.mkdir.mockRejectedValueOnce(new Error("EACCES"));
+ const { configuration } = withLauncher();
+ const pool = new ServerBrowserContexts(configuration);
+ await expect(pool.contextFor("work/team")).rejects.toThrow("EACCES");
+ expect(configuration.launcher).not.toHaveBeenCalled();
+ });
+
it("clears a profile by closing its open context before deleting its storage", async () => {
const human = makeContext();
const browser = makeBrowser();
diff --git a/apps/server/src/preview/ServerBrowserContexts.ts b/apps/server/src/preview/ServerBrowserContexts.ts
index 0e0f71d4e53..9f3fd484307 100644
--- a/apps/server/src/preview/ServerBrowserContexts.ts
+++ b/apps/server/src/preview/ServerBrowserContexts.ts
@@ -17,6 +17,13 @@ const loadPlaywright = () =>
interface Options {
readonly profilesDir: string;
readonly executable: () => Promise<string>;
+ /**
+ * A path that starts `executable`, such as one that moves Chrome out of the server's cgroup.
+ * Released after the whole launch call, since Playwright retries the same path after a glibc race.
+ */
+ readonly launcher?: (
+ executable: string,
+ ) => Promise<{ readonly path: string; readonly release: () => Promise<void> } | undefined>;
readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
readonly env?: NodeJS.ProcessEnv;
readonly onContextClose?: (context: BrowserContext) => void;
@@ -79,10 +86,10 @@ export class ServerBrowserContexts {
}
private async launchOptions() {
- const executablePath = await this.options.executable();
+ const executable = await this.options.executable();
const env = this.options.env ?? process.env;
return {
- executablePath,
+ executable,
env,
args: [
"--disable-gpu",
@@ -96,19 +103,26 @@ export class ServerBrowserContexts {
};
}
- private async launch<A>(options: { readonly executablePath: string }, start: () => Promise<A>) {
+ private async launch<A>(executable: string, start: (executablePath: string) => Promise<A>) {
+ let release: (() => Promise<void>) | undefined;
try {
- return await start();
+ const launcher = await this.options.launcher?.(executable);
+ release = launcher?.release;
+ return await start(launcher?.path ?? executable);
} catch (cause) {
- throw (await this.options.diagnose?.(options.executablePath, cause)) ?? cause;
+ throw (await this.options.diagnose?.(executable, cause)) ?? cause;
+ } finally {
+ await release?.().catch(constVoid);
}
}
private sharedBrowser() {
if (!this.browser) {
- const launched = this.launchOptions().then(async (options) => {
+ const launched = this.launchOptions().then(async ({ executable, ...options }) => {
const { chromium } = loadPlaywright();
- const browser = await this.launch(options, () => chromium.launch(options));
+ const browser = await this.launch(executable, (executablePath) =>
+ chromium.launch({ ...options, executablePath }),
+ );
browser.on("disconnected", () => {
if (this.browser === launched) this.browser = undefined;
});
@@ -156,11 +170,15 @@ export class ServerBrowserContexts {
return browser.newContext(contextOptions);
}
const directory = this.profileDirectory(profileId);
- const options = await this.launchOptions();
- const { chromium } = loadPlaywright();
await NodeFSP.mkdir(directory, { recursive: true });
- return this.launch(options, () =>
- chromium.launchPersistentContext(directory, { ...options, ...contextOptions }),
+ const { executable, ...options } = await this.launchOptions();
+ const { chromium } = loadPlaywright();
+ return this.launch(executable, (executablePath) =>
+ chromium.launchPersistentContext(directory, {
+ ...options,
+ ...contextOptions,
+ executablePath,
+ }),
);
}
diff --git a/docs/user/background-service.md b/docs/user/background-service.md
index be4ad66ff3a..f9ab85fcac4 100644
--- a/docs/user/background-service.md
+++ b/docs/user/background-service.md
@@ -90,6 +90,24 @@ Windows background services are not supported.
T3 Connect can offer service installation during setup, but the two are managed
separately. Signing out of T3 Connect does not stop or uninstall the service.
+## Keep the server responsive when agents use all memory
+
+On Linux, agents already run with lower priority than the server. When they
+fill the machine's memory, though, the kernel may still slow down or stop the
+server, because only an administrator can reserve memory for it. Run, as your
+normal user:
+
+```sh
+t3 service protect
+```
+
+It shows the system settings it will change, asks before applying them, and
+then asks for your sudo password. If the machine runs Tailscale or SSH, it
+also offers to protect them, so you can still reach the machine. Memory
+protection takes effect at once. The server's protection from the kernel's
+out-of-memory killer takes effect after `t3 service restart`. `t3 service status` reports whether
+the protection is in place, and `t3 service protect --undo` removes it.
+
## Troubleshooting
Start with `t3 service status` on the host. It prints the log path and, on Linux,
diff --git a/packages/shared/src/AgentScope.test.ts b/packages/shared/src/AgentScope.test.ts
index cf3ca64acce..2d9aca5ac11 100644
--- a/packages/shared/src/AgentScope.test.ts
+++ b/packages/shared/src/AgentScope.test.ts
@@ -1,9 +1,12 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeChildProcess from "node:child_process";
+import * as NodeFS from "node:fs";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
import { describe, expect, it } from "@effect/vitest";
-import { AGENT_OOM_SCORE_ADJ, agentScopeCommand } from "./AgentScope.ts";
+import { AGENT_OOM_SCORE_ADJ, agentScopeCommand, agentScopeLauncherScript } from "./AgentScope.ts";
import * as HostProcess from "./HostProcess.ts";
describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("agentScopeCommand", () => {
@@ -25,5 +28,20 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("agentScopeComm
expect(Number(pid)).toBe(child.pid);
expect(Number(score)).toBe(AGENT_OOM_SCORE_ADJ);
expect(args).toEqual(["a b", "$HOME"]);
+
+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-launcher-"));
+ try {
+ const launcher = NodePath.join(directory, "launch's");
+ NodeFS.writeFileSync(launcher, agentScopeLauncherScript(launch), { mode: 0o700 });
+ const launched = NodeChildProcess.spawnSync(launcher, ["--flag", "it's"], {
+ encoding: "utf8",
+ });
+ const [launchedPid, launchedScore, ...launchedArgs] = launched.stdout.trimEnd().split("\n");
+ expect(Number(launchedPid)).toBe(launched.pid);
+ expect(Number(launchedScore)).toBe(AGENT_OOM_SCORE_ADJ);
+ expect(launchedArgs).toEqual(["a b", "$HOME", "--flag", "it's"]);
+ } finally {
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ }
});
});
diff --git a/packages/shared/src/AgentScope.ts b/packages/shared/src/AgentScope.ts
index 361bfc49108..ce2d58c017b 100644
--- a/packages/shared/src/AgentScope.ts
+++ b/packages/shared/src/AgentScope.ts
@@ -74,6 +74,14 @@ export interface AgentSystemdScope {
readonly options: ReadonlyArray<string>;
}
+const quoteShell = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
+
+/** An executable file for launchers that take a path, not a command line, such as Playwright. */
+export function agentScopeLauncherScript(launch: AgentScopeCommand): string {
+ const command = [launch.command, ...launch.args].map(quoteShell).join(" ");
+ return `#!/bin/sh\nexec ${command} "$@"\n`;
+}
+
/** Exec at every step preserves the agent PID, stdio, and signals; systemd-run places it and descendants in the scope. */
export function agentScopeCommand(input: {
readonly command: string;